-
Notifications
You must be signed in to change notification settings - Fork 9
/
ft_itoa.c
77 lines (71 loc) · 1.68 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: rchallie <rchallie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/10 15:29:57 by rchallie #+# #+# */
/* Updated: 2019/10/23 10:55:12 by rchallie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_estim(long n)
{
size_t estim;
int isneg;
estim = 0;
isneg = 0;
if (n < 0)
{
estim++;
isneg++;
n = -n;
}
while (n >= 1)
{
estim++;
n /= 10;
}
return (estim);
}
static char *ft_gen(char *rtn, long nbr, int len, int isneg)
{
if (nbr != 0)
rtn = malloc(sizeof(char) * (len + 1));
else
return (rtn = ft_strdup("0"));
if (!rtn)
return (0);
isneg = 0;
if (nbr < 0)
{
isneg++;
nbr = -nbr;
}
rtn[len] = '\0';
while (--len)
{
rtn[len] = (nbr % 10) + '0';
nbr /= 10;
}
if (isneg == 1)
rtn[0] = '-';
else
rtn[0] = (nbr % 10) + '0';
return (rtn);
}
char *ft_itoa(int n)
{
int len;
char *rtn;
long nbr;
int isneg;
nbr = n;
len = ft_estim(nbr);
rtn = 0;
isneg = 0;
if (!(rtn = ft_gen(rtn, nbr, len, isneg)))
return (0);
return (rtn);
}