-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
67 lines (61 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mwilliam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/03 12:16:27 by mwilliam #+# #+# */
/* Updated: 2016/12/04 16:45:17 by mwilliam ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
** Allocates with malloc and returns a "fresh" string ending with '\0'
** which represents the integer n given as argument
*/
static int ft_intcount(int n)
{
long ln;
int count;
ln = n;
count = 0;
if (ln == 0)
count++;
while (ln < 0)
{
ln = -n;
count++;
}
while (ln > 0)
{
count++;
ln /= 10;
}
return (count);
}
char *ft_itoa(int n)
{
char *str;
size_t len;
if (n == -2147483648)
return (ft_strdup("-2147483648"));
len = ft_intcount(n) + 1;
if (!(str = (char *)malloc(sizeof(char) * len)))
return (NULL);
if (n == 0)
str[0] = '0';
if (n < 0)
{
str[0] = '-';
n = -n;
}
str[len - 1] = '\0';
while (n != 0)
{
len--;
str[len - 1] = (n % 10) + '0';
n /= 10;
}
return (str);
}