-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
66 lines (59 loc) · 1.53 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mrios-es <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/13 19:05:11 by mrios-es #+# #+# */
/* Updated: 2023/09/13 19:05:11 by mrios-es ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_chars(int nb)
{
long nbr;
int count;
nbr = nb;
count = 1;
if (nbr < 0)
{
count++;
nbr = -nbr;
}
while (nbr >= 10)
{
count++;
nbr /= 10;
}
return (count);
}
static void fill_str(char *str, int nb, int size)
{
long nbr;
int is_negative;
nbr = nb;
is_negative = nbr < 0;
if (is_negative)
{
str[0] = '-';
nbr = -nbr;
}
while (size > is_negative)
{
size--;
str[size] = nbr % 10 + '0';
nbr /= 10;
}
}
char *ft_itoa(int n)
{
int size;
char *n_str;
size = count_chars(n);
n_str = ft_calloc((size + 1), sizeof(char));
if (!n_str)
return (NULL);
fill_str(n_str, n, size);
return (n_str);
}