-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
58 lines (52 loc) · 1.47 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: malexand <malexand@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/21 15:57:14 by aguemy #+# #+# */
/* Updated: 2017/09/26 18:05:06 by malexand ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int absolute(int n)
{
if (n < 0)
return (-n);
else
return (n);
}
static int alloc_me(char **str, int n)
{
int i;
i = 0;
if (n < 0)
i = 1;
while (n < -9 || n > 9)
{
n = n / 10;
i++;
}
if (!(*str = (char*)malloc(sizeof(char) * (i + 2))))
return (0);
(*str)[i + 1] = '\0';
return (i + 1);
}
char *ft_itoa(int n)
{
int j;
char *str;
if (!(j = alloc_me(&str, n)))
return (NULL);
while (n < -9 || n > 9)
{
str[j - 1] = absolute(n % 10) + 48;
n = n / 10;
j--;
}
str[j - 1] = absolute(n % 10) + 48;
if (n < 0)
str[0] = '-';
return (str);
}