-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
73 lines (66 loc) · 1.61 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ashongwe <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/06 14:47:52 by ashongwe #+# #+# */
/* Updated: 2019/06/13 15:28:10 by ashongwe ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_num_len(int num)
{
int len;
len = 1;
if (num < 0)
{
len++;
num *= -1;
}
while (num > 9)
{
num /= 10;
len++;
}
return (len);
}
static int ft_div(int len)
{
int div;
div = 1;
if (len == 1)
return (1);
while (len > 1)
{
div *= 10;
len--;
}
return (div);
}
char *ft_itoa(int n)
{
int ctrl;
int len;
int maxlen;
char *res;
len = ft_num_len(n);
maxlen = len;
if (!(res = (char*)malloc(sizeof(char) * (len + 1))))
return (NULL);
if (n == -2147483648)
return (ft_strdup("-2147483648"));
ctrl = 0;
if (n < 0)
{
n *= -1;
res[0] = '-';
ctrl++;
len--;
}
while (ctrl < maxlen)
res[ctrl++] = (((n / ft_div(len--)) % 10) + 48);
res[ctrl++] = '\0';
return (res);
}