-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
97 lines (88 loc) · 1.92 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dapetros <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/24 22:06:01 by dapetros #+# #+# */
/* Updated: 2024/01/24 22:07:06 by dapetros ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t get_num_size(long num)
{
size_t size;
size = 0;
if (num == 0)
return (1);
while (num)
{
++size;
num /= 10;
}
return (size);
}
static void ft_strrev(char *str, size_t index, size_t i)
{
size_t start;
size_t end;
char temp;
end = i - 1;
start = index;
while (start < end)
{
temp = str[start];
str[start] = str[end];
str[end] = temp;
++start;
--end;
}
}
static void get_str(char *str, size_t index, long num)
{
size_t i;
i = index;
if (num == 0)
{
str[0] = '0';
++i;
}
else
{
while (num != 0)
{
str[i] = (num % 10) + '0';
num /= 10;
++i;
}
}
str[i] = '\0';
ft_strrev(str, index, i);
}
char *ft_itoa(int n)
{
size_t num_size;
size_t start_index;
int sign;
long num;
char *str;
num = n;
sign = 1;
start_index = 0;
num_size = get_num_size(num);
if (num < 0)
{
sign = -1;
start_index = 1;
++num_size;
num = -num;
}
str = (char *)malloc(num_size + 1);
if (!str)
return (NULL);
if (sign == -1)
str[0] = '-';
get_str(str, start_index, num);
return (str);
}