-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
79 lines (71 loc) · 1.84 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: edetoh <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/19 13:16:47 by edetoh #+# #+# */
/* Updated: 2024/10/25 11:11:31 by edetoh ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
* ft_itoa converts an integer to a string.
* Takes 'n' (integer). Returns a string representing
* the integer or NULL on error.
*/
static int ft_int_len(int n)
{
int len;
len = 0;
if (n <= 0)
{
len++;
}
while (n != 0)
{
n = n / 10;
len++;
}
return (len);
}
char *ft_itoa(int n)
{
char *str;
int int_len;
int nb;
if (n == -2147483648)
return (ft_strdup("-2147483648"));
int_len = ft_int_len(n);
str = malloc((int_len + 1) * sizeof(char));
if (!str)
return (NULL);
nb = n;
str[int_len] = 0;
if (n < 0)
{
str[0] = '-';
nb = -nb;
}
if (nb == 0)
str[0] = '0';
while (nb > 0)
{
str[--int_len] = (nb % 10) + '0';
nb = nb / 10;
}
return (str);
}
// #include <string.h>
// #include <stdio.h>
// #include <unistd.h>
// int main(void)
// {
// char *res = ft_itoa(-123456);
// printf("===== RESULT iTOA =====\n");
// printf("Res : %s\n", res);
// printf("=======================\n");
// free(res);
// return (1);
// }