-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
67 lines (61 loc) · 1.57 KB
/
ft_itoa.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nlyamani <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/01 17:47:46 by nlyamani #+# #+# */
/* Updated: 2024/10/01 17:48:22 by nlyamani ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_nbrlen(int n)
{
int n_s;
n_s = 1;
if (n < 0)
{
if (n == C_INT_MIN)
n = C_INT_MAX;
else
n = -n;
n_s++;
}
while (n > 9)
{
n /= 10;
n_s++;
}
return (n_s);
}
static int ft_is_negative(int n)
{
if (n < 0)
return (1);
return (0);
}
char *ft_itoa(int n)
{
int n_s;
int is_negative;
char *str;
if (n == C_INT_MIN)
return (ft_strdup("-2147483648"));
n_s = ft_nbrlen(n);
is_negative = ft_is_negative(n);
str = (char *) malloc(n_s * sizeof(char) + 1);
if (!str)
return (NULL);
str[n_s] = '\0';
if (is_negative)
n = -n;
while (n_s > 0)
{
str[--n_s] = (n % 10) + 48;
n = n / 10;
}
if (is_negative)
str[n_s] = '-';
return (str);
}