-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
69 lines (63 loc) · 1.6 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cborton <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/06 10:37:19 by cborton #+# #+# */
/* Updated: 2020/11/10 21:42:16 by cborton ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static long int ft_abs(long int n)
{
if (n < 0)
return (n * (-1));
return (n);
}
static long int ft_intlen(long int n)
{
size_t len;
len = 0;
if (n == 0)
len = 1;
if (n < 0)
{
len = 1;
n = ft_abs(n);
}
while (n != 0)
{
n = n / 10;
len++;
}
return (len);
}
char *ft_itoa(int n)
{
size_t len;
char *s;
long n_long;
n_long = (long)n;
len = ft_intlen(n_long);
if (!(s = malloc(ft_abs(len) + 1)))
return (NULL);
s[len] = '\0';
if (n_long == 0)
s[0] = '0';
if (n < 0)
{
s[0] = '-';
n_long = ft_abs(n_long);
}
len = ft_abs(len - 1);
n_long = ft_abs(n_long);
while (len >= 0 && n_long != 0)
{
s[len] = n_long % 10 + '0';
n_long = n_long / 10;
len--;
}
return (s);
}