-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
62 lines (57 loc) · 1.44 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Aamjahed <aamjahed@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/01 01:14:53 by Aamjahed #+# #+# */
/* Updated: 2023/10/01 01:15:40 by Aamjahed ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t num_length(int n)
{
int len;
long copy;
if (n == 0)
return (1);
len = 0;
copy = n;
if (copy < 0)
{
++len;
copy = -copy;
}
while (copy > 0)
{
copy /= 10;
++len;
}
return (len);
}
char *ft_itoa(int n)
{
char *a;
long copy;
int len;
len = num_length(n);
a = malloc(sizeof(char) * (len + 1));
if (a == NULL)
return (NULL);
copy = n;
if (copy == 0)
a[0] = '0';
if (copy < 0)
{
a[0] = '-';
copy = -copy;
}
a[len--] = '\0';
while (copy > 0)
{
a[len--] = copy % 10 + '0';
copy /= 10;
}
return (a);
}