-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
72 lines (65 loc) · 1.59 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ctokuyos <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/05 10:31:11 by ctokuyos #+# #+# */
/* Updated: 2024/11/06 15:11:41 by ctokuyos ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *conversion(int len)
{
char *temp;
temp = malloc((len + 1) * sizeof (char));
if (!temp)
return (NULL);
temp[0] = '\0';
return (temp);
}
static int int_len(long nbr)
{
int count;
count = 0;
if (nbr < 0)
{
count++;
nbr = -nbr;
}
if (nbr == 0)
count++;
while (nbr != 0)
{
nbr /= 10;
count++;
}
return (count);
}
char *ft_itoa(int n)
{
char *res;
long nbr;
int len;
int i;
nbr = n;
len = int_len(nbr);
res = conversion(len);
if (!res)
return (NULL);
if (nbr < 0)
nbr = -nbr;
i = len - 1;
if (nbr == 0)
res[i--] = '0';
while (nbr != 0)
{
res[i--] = ((nbr % 10) + '0');
nbr = nbr / 10;
}
if (n < 0)
res[0] = '-';
res[len] = '\0';
return (res);
}