-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
74 lines (66 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
65
66
67
68
69
70
71
72
73
74
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kakiba <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/06/04 17:02:07 by kakiba #+# #+# */
/* Updated: 2022/07/27 15:55:28 by kakiba ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *minus_check(int *n, int *minus, int d);
static char *ft_min(void);
char *ft_itoa(int n)
{
char *s;
int buf;
int i;
int minus;
if (n == INT_MIN)
return (ft_min());
i = 1;
buf = n;
while (buf / 10 != 0)
{
buf = buf / 10;
i++;
}
s = minus_check(&n, &minus, i);
if (s == NULL)
return (NULL);
s[i + minus] = '\0';
while (i > 0)
{
s[i-- + minus - 1] = n % 10 + '0';
n = n / 10;
}
return (s);
}
static char *minus_check(int *n, int *minus, int d)
{
char *s;
if (*n < 0)
{
*minus = 1;
*n = -*n;
}
else
*minus = 0;
s = malloc(sizeof(char) * (d + *minus + 1));
if (s == NULL)
return (NULL);
if (*minus == 1)
s[0] = '-';
return (s);
}
static char *ft_min(void)
{
char *s;
s = malloc(12);
if (s == NULL)
return (NULL);
ft_strlcpy(s, "-2147483648", 13);
return (s);
}