-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
120 lines (109 loc) · 2.25 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sahafid <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/09 16:57:55 by sahafid #+# #+# */
/* Updated: 2021/11/09 16:57:58 by sahafid ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *convertingnegat(long int y, char *a, long int o)
{
long int res;
long int store;
store = 0;
res = o;
while (y > 0)
{
store = res % 10;
a[y] = store + '0';
store = 0;
res = o / 10;
o = res;
y--;
}
return (a);
}
static char *convertingpos(long int y, char *a, int n)
{
long int res;
long int store;
store = 0;
res = n;
while (y > 0)
{
store = res % 10;
a[y - 1] = store + '0';
store = 0;
res = n / 10;
n = res;
y--;
}
return (a);
}
static char *negatifcase(int n, long int y)
{
char *a;
long int res;
long int o;
long int l;
res = n;
o = (long int)n;
while (o != '\0')
{
o = o / 10;
y++;
}
l = y;
a = (char *)malloc((y + 2) * sizeof(char));
if (!a)
return (0);
a[0] = '-';
res = res * -1;
o = res;
a = convertingnegat(y, a, o);
a[l + 1] = '\0';
return (a);
}
static char *positifcase(int n, long int y)
{
long int res;
long int l;
char *a;
res = n;
while (n != '\0')
{
n = n / 10;
y++;
}
l = y;
a = (char *)malloc((y + 1) * sizeof(char));
if (!a)
return (0);
n = res;
a = convertingpos(y, a, n);
a[l] = '\0';
return (a);
}
char *ft_itoa(int n)
{
char *a;
long int y;
y = 0;
if (n == 0)
{
a = (char *)malloc(2 * sizeof(char));
if (!a)
return (0);
a[0] = '0';
a[1] = '\0';
return (a);
}
if (n > 0)
return (positifcase(n, y));
else
return (negatifcase(n, y));
}