-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
73 lines (66 loc) · 1.64 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
68
69
70
71
72
73
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tedison <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/03 09:35:06 by tedison #+# #+# */
/* Updated: 2021/04/05 11:42:42 by tedison ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_myputnbr(int n, char *arr, int *c)
{
unsigned int nbr;
nbr = n;
if (n < 0)
{
arr[0] = '-';
*c = *c + 1;
nbr = -nbr;
}
if (nbr < 10)
{
arr[*c] = nbr + '0';
*c = *c + 1;
}
else
{
ft_myputnbr(nbr / 10, arr, c);
ft_myputnbr(nbr % 10, arr, c);
}
}
size_t count_digits(int n)
{
size_t count;
unsigned int nbr;
count = 0;
if (n == 0)
return (1);
nbr = n;
if (n < 0)
{
count++;
nbr = -n;
}
while (nbr > 0)
{
count++;
nbr /= 10;
}
return (count);
}
char *ft_itoa(int n)
{
char *to_return;
int index;
index = 0;
to_return = NULL;
to_return = malloc(sizeof(*to_return) * (count_digits(n) + 1));
if (!to_return)
return (NULL);
ft_myputnbr(n, to_return, &index);
to_return[index] = '\0';
return (to_return);
}