-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
67 lines (61 loc) · 1.55 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
64
65
66
67
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ahmaymou <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/08 17:26:42 by ahmaymou #+# #+# */
/* Updated: 2022/10/26 17:05:12 by ahmaymou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_get_len(long nbr)
{
int b;
b = 0;
if (!nbr)
b = 1;
else if (nbr < 0)
{
nbr *= (-1);
b++;
}
while (nbr > 0)
{
nbr = nbr / 10;
b++;
}
return (b);
}
static char *ft_convert(long nbr, char *s, int lennbr)
{
if (nbr < 0)
{
nbr *= (-1);
s[0] = '-';
}
else if (!nbr)
s[0] = '0';
while (nbr != 0)
{
s[lennbr] = (nbr % 10) + '0';
nbr = nbr / 10;
lennbr--;
}
return (s);
}
char *ft_itoa(int n)
{
int lennbr;
int nbr;
char *s;
nbr = n;
lennbr = ft_get_len(nbr) - 1;
s = (char *)malloc((lennbr + 2) * sizeof(char));
if (!s)
return (NULL);
s[lennbr + 1] = '\0';
s = ft_convert(nbr, s, lennbr);
return (s);
}