-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathft_itoa.c
69 lines (62 loc) · 1.59 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adiaz-lo <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/01/13 11:35:20 by adiaz-lo #+# #+# */
/* Updated: 2020/01/13 11:42:11 by adiaz-lo ### ########.fr */
/* */
/* ************************************************************************** */
/*
** This function converts an integer ('i') into a string ('str').
*/
#include "libft.h"
/*
** This auxiliary function counts the digits of the long integer received by
** parameter.
*/
static int ft_digit_count(long int i)
{
int count;
count = 0;
if (i < 0)
{
i *= -1;
count++;
}
while (i > 0)
{
i /= 10;
count++;
}
return (count);
}
char *ft_itoa(int n)
{
char *str;
int i;
long int nb;
nb = n;
i = ft_digit_count(nb);
if (!(str = malloc(i * sizeof(char) + 1)))
return (0);
str[i--] = 0;
if (nb == 0)
{
str = ft_calloc(2, sizeof(char));
str[0] = 48;
}
if (nb < 0)
{
str[0] = '-';
nb = nb * -1;
}
while (nb > 0)
{
str[i--] = nb % 10 + '0';
nb = nb / 10;
}
return (str);
}