-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
66 lines (60 loc) · 1.47 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: brpereir <brpereir@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/11 21:50:11 by brpereir #+# #+# */
/* Updated: 2023/04/23 17:59:30 by brpereir ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static long int count(long int n)
{
int count;
count = 0;
if (n == 0)
return (1);
if (n < 0)
{
n = -n;
count++;
}
while (n)
{
count++;
n /= 10;
}
return (count);
}
static char *if_zero(char *str)
{
str[0] = '0';
return (str);
}
char *ft_itoa(int n)
{
int num;
char *c;
long int nb;
nb = n;
num = count(nb);
c = (char *)malloc(sizeof(char) * (num + 1));
if (!c)
return (NULL);
c[num--] = '\0';
if (nb == 0)
return (if_zero(c));
if (nb < 0)
{
c[0] = '-';
nb = -nb;
}
while (nb > 0)
{
c[num--] = (nb % 10) + 48;
nb /= 10;
}
return (c);
}