-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
79 lines (72 loc) · 1.69 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
74
75
76
77
78
79
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: wleite <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/28 17:32:26 by wleite #+# #+# */
/* Updated: 2021/07/28 23:41:46 by wleite ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_digits(int n)
{
int i;
i = 0;
if (n < 0)
{
n = -n;
i++;
}
while (n)
{
n = n / 10;
i++;
}
return (i);
}
static void ft_strrev(char *str)
{
char temp;
int start;
int end;
start = 0;
end = ft_strlen(str) - 1;
if (str[start] == '-')
start++;
while (str[start] && start < end)
{
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
char *ft_itoa(int n)
{
char *res;
int i;
if (n == 0)
return (ft_strdup("0"));
if (n == INT_MIN)
return (ft_strdup("-2147483648"));
res = (char *)malloc(sizeof(char) * (ft_count_digits(n) + 1));
if (!res)
return (NULL);
i = 0;
if (n < 0)
{
n = -n;
res[i++] = '-';
}
while (n)
{
res[i++] = (n % 10) + '0';
n = n / 10;
}
res[i] = '\0';
ft_strrev(res);
return (res);
}