-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
63 lines (57 loc) · 1.45 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpaaso <tpaaso@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/26 15:30:17 by tpaaso #+# #+# */
/* Updated: 2022/04/11 12:35:26 by tpaaso ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_count(int nb)
{
int i;
long n;
i = 1;
n = nb;
if (n < 0)
{
n *= -1;
i++;
}
while (10 <= n)
{
n /= 10;
i++;
}
return (i);
}
int ft_absolute(int nbr)
{
if (nbr < 0)
return (-nbr);
return (nbr);
}
char *ft_itoa(int n)
{
char *res;
size_t len;
len = (size_t)ft_count(n);
res = (char *)malloc(sizeof(char) * (len + 1));
if (res == NULL)
return (NULL);
res[len] = '\0';
if (n < 0)
res[0] = '-';
else if (n == 0)
res[0] = '0';
while (n != 0)
{
len--;
res[len] = (char)ft_absolute(n % 10) + '0';
n = n / 10;
}
return (res);
}