-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
77 lines (70 loc) · 1.87 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmaraval <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/15 07:43:53 by tmaraval #+# #+# */
/* Updated: 2017/11/20 08:08:58 by tmaraval ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *ft_itoa_neg(int n, int cntdigit)
{
char *ret;
long nb;
nb = (long)n;
if (nb == 0)
{
if ((ret = (char *)malloc(sizeof(char) * 2)) == NULL)
return (NULL);
ret[0] = '0';
ret[1] = '\0';
return (ret);
}
if ((ret = (char *)malloc(sizeof(char) * cntdigit + 2)) == NULL)
return (NULL);
ret[0] = '-';
nb = nb * -1;
ret[cntdigit + 1] = '\0';
while (cntdigit > 0)
{
ret[cntdigit] = (nb % 10) + '0';
nb = nb / 10;
cntdigit--;
}
return (ret);
}
static char *ft_itoa_pos(int n, int cntdigit)
{
char *ret;
if ((ret = (char *)malloc(sizeof(char) * cntdigit + 1)) == NULL)
return (NULL);
ret[cntdigit] = '\0';
while (cntdigit > 0)
{
ret[cntdigit - 1] = (n % 10) + '0';
n = n / 10;
cntdigit--;
}
return (ret);
}
char *ft_itoa(int n)
{
int cntdigit;
long nb;
char *ret;
nb = n;
cntdigit = 0;
while (nb != 0)
{
nb = nb / 10;
cntdigit++;
}
if (n > 0)
ret = ft_itoa_pos(n, cntdigit);
else
ret = ft_itoa_neg(n, cntdigit);
return (ret);
}