-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
64 lines (58 loc) · 1.7 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mavinici <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/22 18:24:43 by mavinici #+# #+# */
/* Updated: 2021/05/22 18:24:43 by mavinici ### ########.fr */
/* */
/* ************************************************************************** */
#include <libft.h>
static int is_negative(int number)
{
if (number < 0)
return (1);
else
return (0);
}
static int count_digits(unsigned int number)
{
int count;
count = 0;
if (number == 0)
return (1);
while (number >= 1)
{
number /= 10;
count++;
}
return (count);
}
char *ft_itoa(int n)
{
char *str;
unsigned int negative;
unsigned int number;
unsigned int digits;
negative = is_negative(n);
if (negative == 1)
number = -n;
else
number = n;
digits = count_digits(number);
str = (char *)malloc(digits + negative + 1);
if (str == NULL)
return (NULL);
if (negative == 1)
str[0] = '-';
str[digits + negative] = '\0';
while (digits > 0)
{
str[(digits - 1) + negative] = (number % 10) + '0';
number /= 10;
digits--;
}
return (str);
}