-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
65 lines (58 loc) · 1.5 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: youkim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/05/10 10:42:30 by youkim #+# #+# */
/* Updated: 2021/05/10 11:39:10 by youkim ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int st_sign(long n)
{
if (n < 0)
return (-1);
return (1);
}
static int st_abs(long n)
{
if (n >= 0)
return (n);
else
return (-n);
}
static size_t st_digitlen(long n)
{
size_t len;
len = 0;
if (!n || st_sign(n) == -1)
len++;
while (n)
{
n /= 10;
len++;
}
return (len);
}
char *ft_itoa(int n)
{
int len;
int sign;
char *str;
sign = st_sign(n);
len = st_digitlen(n);
str = malloc((len + 1) * sizeof(char));
if (!str)
return (0);
str[len] = 0;
while (--len >= 0)
{
str[len] = st_abs(n % 10) + '0';
n = st_abs(n / 10);
}
if (sign == -1)
str[0] = '-';
return (str);
}