-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
62 lines (57 loc) · 1.44 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpeters <[email protected] +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/29 17:16:19 by tpeters #+# #+# */
/* Updated: 2022/04/08 15:15:29 by tpeters ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int num_len(long n)
{
int len;
len = 0;
if (n == 0)
return (1);
if (n < 0)
{
n *= -1;
len++;
}
while (n != 0)
{
n /= 10;
len++;
}
return (len);
}
char *ft_itoa(int n)
{
char *p;
int is_neg;
long num;
int len;
num = n;
len = num_len(num) - 1;
p = (char *)malloc(len + 1 + 1);
if (!p)
return (NULL);
p[len + 1] = '\0';
is_neg = (num < 0);
if (is_neg)
num *= -1;
while (len > 0)
{
p[len] = '0' + (num % 10);
len--;
num /= 10;
}
if (is_neg)
p[len] = '-';
else
p[len] = '0' + (num % 10);
return (p);
}