-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
65 lines (60 loc) · 1.53 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: tchevrie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/12 17:53:25 by tchevrie #+# #+# */
/* Updated: 2022/10/05 04:32:47 by tchevrie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t count_size(long nb)
{
size_t size;
size = 0;
if (nb < 0)
{
nb = nb * (-1);
size = 1;
}
if (nb == 0)
size = 1;
else
{
while (nb)
{
nb = nb / 10;
size++;
}
}
return (size);
}
char *ft_itoa(int n)
{
size_t size;
long nb;
char *str;
int is_negative;
size = count_size((long) n);
str = (char *) malloc(sizeof(char) * (size + 1));
if (str == NULL)
return (NULL);
nb = (long) n;
is_negative = 0;
if (nb < 0)
{
nb = nb * (-1);
str[0] = '-';
is_negative = 1;
}
str[size] = '\0';
while (size > (size_t) is_negative)
{
str[size - 1] = nb % 10 + '0';
nb = nb / 10;
size--;
}
return (str);
}