-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
65 lines (57 loc) · 910 Bytes
/
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
#include "libft.h"
static int count_dig(int n)
{
int dig;
dig = 1;
while ((n /= 10) != 0)
dig++;
return (dig);
}
static unsigned long count_pow(int n)
{
unsigned long pow;
pow = 10;
while ((n /= 10) != 0)
pow *= 10;
return (pow);
}
static char *ret_nbr(int n)
{
unsigned long pow;
char *res;
int digits;
int i;
pow = count_pow(n);
digits = count_dig(n);
i = 0;
if (n < 0)
{
digits++;
res = (char *)malloc((sizeof(char) * digits) + 1);
if (!res)
return (NULL);
res[i++] = '-';
n *= -1;
}
else
res = (char *)malloc((sizeof(char) * digits) + 1);
if (!res)
return (NULL);
while (i < digits && ((pow /= 10) != 0))
res[i++] = ((n / pow) % 10) + '0';
res[i] = '\0';
return (res);
}
char *ft_itoa(int n)
{
char *res;
if (n != -2147483648)
res = ret_nbr(n);
else
{
n++;
res = ret_nbr(n);
res[ft_strlen(res) - 1]++;
}
return (res);
}