-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
55 lines (50 loc) · 1.46 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thifranc <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/12 15:39:04 by thifranc #+# #+# */
/* Updated: 2016/03/12 16:14:45 by thifranc ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_nb_len(int n)
{
if (0 <= n && n <= 9)
return (1);
else
return (1 + ft_nb_len(n / 10));
}
static int ft_sign(int *n)
{
if (*n < 0)
{
*n = -*n;
return (1);
}
else
return (0);
}
char *ft_itoa(int n)
{
int size;
int sign;
char *out;
if (n == -2147483647 - 1)
return (ft_strdup("-2147483648"));
sign = ft_sign(&n);
size = ft_nb_len(n) + sign;
if (!(out = (char*)malloc(sizeof(char) * size + 1)))
return (NULL);
out[size] = '\0';
while (size--)
{
out[size] = n % 10 + 48;
n /= 10;
}
if (sign == 1)
out[0] = '-';
return (out);
}