-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
88 lines (76 loc) · 1.91 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hicunha- <hicunha-@student.42porto.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/06 13:46:02 by hicunha- #+# #+# */
/* Updated: 2023/10/06 13:46:02 by hicunha- ### ########.fr */
/* */
/* ************************************************************************** */
/*
The ft_itoa() function converts the int number to a string with the correct
memory allocation, terminated by NULL, except that ft_itoa() does not detect
malloc() errors.
Return the converted value.
*/
#include <limits.h>
#include "libft.h"
static size_t num_len(int n)
{
size_t i;
i = 0;
if (n < 0)
{
n *= -1;
i++;
}
while (n > 9)
{
n = n / 10;
i++;
}
return (i + 1);
}
static char *num_str(size_t len, int n, char *num)
{
size_t j;
j = 0;
num[len] = '\0';
if (n < 0)
{
num[0] = '-';
n *= -1;
j = 1;
}
while (len > j)
{
len--;
num[len] = n % 10 + 48;
n = n / 10;
}
return (num);
}
char *ft_itoa(int n)
{
char *num;
size_t i;
if (n == INT_MIN)
return (ft_strdup("-2147483648"));
i = num_len(n);
num = malloc(sizeof(char) * (i + 1));
if (!num)
return (NULL);
num_str(i, n, num);
return (num);
}
/*#include <stdio.h>
#include <limits.h>
int main()
{
int n;
n = 0;
printf("%s", ft_itoa(n));
return (0);
}*/