-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
61 lines (55 loc) · 1.62 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ryebadok <ryebadok@student.42quebec> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/07 10:08:38 by ryebadok #+# #+# */
/* Updated: 2021/05/17 11:25:55 by ryebadok ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_charcount(int n)
{
int count;
count = 1;
while (n / 10 != 0)
{
n = n / 10;
count++;
}
return (count);
}
void ft_savenbr(char *dest, int nb, int pos)
{
pos -= 1;
if (nb / 10 != 0)
ft_savenbr(dest, nb / 10, pos);
if (nb % 10 < 0)
dest[pos] = (-(nb % 10)) + '0';
else
dest[pos] = (nb % 10) + '0';
}
char *ft_itoa(int n)
{
char *rtn;
if (n >= 0)
{
rtn = malloc(sizeof(char) * (ft_charcount(n) + 1));
if (!rtn)
return (NULL);
ft_savenbr(rtn, n, ft_charcount(n));
rtn[ft_charcount(n)] = '\0';
}
else
{
rtn = malloc(sizeof(char) * (ft_charcount(n) + 2));
if (!rtn)
return (NULL);
rtn[0] = '-';
ft_savenbr(rtn, n, ft_charcount(n) + 1);
rtn[ft_charcount(n) + 1] = '\0';
}
return (rtn);
}