forked from hidaehyunlee/Libft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
55 lines (49 loc) · 1.42 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: daelee <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/05 17:51:44 by daelee #+# #+# */
/* Updated: 2020/04/10 11:29:48 by daelee ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
long int ft_abs(long int nbr)
{
return ((nbr < 0) ? -nbr : nbr);
}
int ft_len(long int nbr)
{
int len;
len = (nbr <= 0) ? 1 : 0;
while (nbr != 0)
{
nbr = nbr / 10;
len++;
}
return (len);
}
char *ft_itoa(int n)
{
int len;
int sign;
char *c;
sign = (n < 0) ? -1 : 1;
len = ft_len(n);
c = (char *)malloc(sizeof(char) * len + 1);
if (c == NULL)
return (0);
c[len] = '\0';
len--;
while (len >= 0)
{
c[len] = '0' + ft_abs(n % 10);
n = ft_abs(n / 10);
len--;
}
if (sign == -1)
c[0] = '-';
return (c);
}