-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
63 lines (57 loc) · 1.5 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jsprouts <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/09/25 02:48:41 by jsprouts #+# #+# */
/* Updated: 2019/09/25 16:24:43 by jsprouts ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_size(int n)
{
int ln;
ln = 0;
if (n < 0)
ln++;
while (n != 0)
{
n /= 10;
ln++;
}
return (ln);
}
static void ft_help(char *str, int *n, int *ln, int *neg)
{
str[*ln] = (*n % 10) * -1 + '0';
*ln -= 1;
*n /= -10;
*neg = -1;
}
char *ft_itoa(int n)
{
int ln;
char *str;
int i;
int neg;
i = 0;
neg = 0;
ln = ft_size(n);
if (ln == 0)
ln++;
if (!(str = (char*)malloc(sizeof(char) * (ln + 1))))
return (NULL);
str[ln--] = 0;
if (n < 0)
ft_help(str, &n, &ln, &neg);
while (ln >= 0)
{
str[ln--] = n % 10 + '0';
n /= 10;
}
if (neg == -1)
str[0] = '-';
return (str);
}