-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
87 lines (80 loc) · 1.83 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
80
81
82
83
84
85
86
87
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: toramo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/30 09:26:40 by toramo #+# #+# */
/* Updated: 2023/10/31 12:41:05 by toramo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int int_str_size(int n)
{
int i;
i = 0;
if (n == 0)
return (2);
if (n < 0)
{
i++;
n = n * -1;
}
while (n > 0)
{
n = n / 10;
i++;
}
i++;
return (i);
}
char *ft_itoa_array(int n, char *result, int i, int j)
{
char *str;
str = malloc(sizeof(char) * int_str_size(n));
if (!str)
{
free(result);
return (0);
}
if (n < 0)
{
result[j++] = '-';
n = n * -1;
}
while (n != 0)
{
str[i++] = n % 10 + 48;
n = n / 10;
}
i--;
while (i + 1)
result[j++] = str[i--];
result[j] = 0;
free (str);
return (result);
}
char *ft_itoa(int n)
{
char *result;
if (n == -2147483648)
result = malloc(sizeof(char) * 12);
else
result = malloc(sizeof(char) * int_str_size(n));
if (result != 0)
{
if (n == 0)
{
ft_strlcpy(result, "0", 2);
return (result);
}
if (n == -2147483648)
{
ft_strlcpy(result, "-2147483648", 12);
return (result);
}
result = ft_itoa_array(n, result, 0, 0);
}
return (result);
}