-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
59 lines (54 loc) · 1.57 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jergoh <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/21 10:18:42 by jergoh #+# #+# */
/* Updated: 2023/09/21 10:18:43 by jergoh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_countdigits(int n)
{
int result;
result = 0;
if (n < 0)
{
result++;
n *= -1;
}
else if (n == 0)
return (1);
while ((unsigned int)n > 0)
{
result++;
n = (unsigned int)n / 10;
}
return (result);
}
char *ft_itoa(int n)
{
char *result;
int num_digits;
num_digits = ft_countdigits(n);
result = malloc((num_digits + 1) * sizeof(char));
if (result == NULL)
return (NULL);
if (n == 0)
result[0] = '0';
if (n < 0)
{
result[0] = '-';
n *= -1;
}
result[num_digits] = '\0';
while ((num_digits - 1) >= 0 && (unsigned int)n > 0)
{
result[num_digits - 1] = ((unsigned int)n % 10) + '0';
n = (unsigned int)n / 10;
num_digits--;
}
return (result);
}