-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
106 lines (95 loc) · 2.06 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ael-haib <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/13 13:33:24 by ael-haib #+# #+# */
/* Updated: 2024/01/24 12:10:56 by ael-haib ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int count_digits(int num)
{
int count;
count = 0;
while (num != 0)
{
num /= 10;
count++;
}
return (count);
}
char *allocate_result(int num, int count)
{
char *result;
result = NULL;
if (num == 0)
{
result = (char *)malloc(2 * sizeof(char));
if (result != NULL)
{
result[0] = '0';
result[1] = '\0';
}
}
else
{
result = (char *)malloc((count + 1) * sizeof(char));
}
return (result);
}
void fill_result(char *result, long int n, int count)
{
int i;
i = (count - 1);
while (i >= 0)
{
result[i] = (n % 10) + '0';
n /= 10;
i--;
}
}
char *ft_itoa(int num)
{
long int n;
char *result;
int count;
count = count_digits(num);
if (num < 0)
{
count++;
n = (long int)num * -1;
}
else
n = num;
result = allocate_result(num, count);
if (result != NULL)
{
fill_result(result, n, count);
if (num < 0)
result[0] = '-';
if (count)
result[count] = '\0';
}
return (result);
}
/* int main(void)
{
int num;
char *str;
num = 0;
str = ft_itoa(num);
if (str != NULL)
{
printf("Integer: %d\n", num);
printf("String: %s\n", str);
free(str);
}
else
{
printf("Memory allocation error\n");
}
return (0);
} */