-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
57 lines (52 loc) · 1.53 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: meldora <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/04 18:16:50 by meldora #+# #+# */
/* Updated: 2020/11/14 13:37:57 by meldora ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_nlen(int n)
{
int i;
if (n == 0)
return (1);
i = 0;
while (n)
{
i++;
n /= 10;
}
return (i);
}
char *ft_itoa(int n)
{
char *res;
int len;
int sign;
sign = n >= 0 ? 0 : 1;
if (n == -2147483648)
{
if (!(res = (char *)malloc(sizeof(char) * 12)))
return (NULL);
return (res = ft_memcpy(res, "-2147483648", 12));
}
n = n >= 0 ? n : n * -1;
len = ft_nlen(n) + sign;
if (!(res = (char *)malloc(sizeof(char) * (len + 1))))
return (NULL);
res[0] = sign == 0 ? res[0] : '-';
res[0] = n == 0 ? '0' : res[0];
res[len--] = '\0';
while (n)
{
res[len] = n % 10 + '0';
n /= 10;
len--;
}
return (res);
}