-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
63 lines (58 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
56
57
58
59
60
61
62
63
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jaqrodri <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/04 01:58:44 by jaqrodri #+# #+# */
/* Updated: 2021/06/07 21:49:04 by jaqrodri ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int cont_num(int n)
{
int i;
unsigned int nb;
i = 0;
if (n < 0)
{
i++;
nb = n * (-1);
}
else
nb = n;
while (nb > 0)
{
nb = nb / 10;
i++;
}
return (i);
}
char *ft_itoa(int n)
{
char *s;
int num;
unsigned int nb;
num = cont_num(n);
s = (char *)malloc((num + 1) * sizeof(char));
if (s == NULL)
return (NULL);
if (n == 0)
return (ft_substr("0", 0, 1));
if (n < 0)
{
s[0] = '-';
nb = n * (-1);
}
else
nb = n;
s[num--] = '\0';
while (num > 0 || nb > 0)
{
s[num] = (nb % 10) + '0';
nb = nb / 10;
num--;
}
return (s);
}