-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
executable file
·68 lines (62 loc) · 1.55 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
67
68
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmasstou <mmasstou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/10 18:38:06 by mmasstou #+# #+# */
/* Updated: 2021/11/14 19:13:03 by mmasstou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_nbrlen(int n)
{
int size;
size = 0;
if (n == 0)
return (1);
if (n <= 0)
{
n = -n;
size++;
}
while (n != 0)
{
n /= 10;
size++;
}
return (size);
}
static int ft_signe(int n)
{
if (n < 0)
return (1);
return (0);
}
char *ft_itoa(int n)
{
char *str;
int nbrlen;
unsigned int nbr;
nbr = n;
nbrlen = ft_nbrlen(n);
if (nbrlen == 0)
nbrlen = 1;
str = (char *)malloc((nbrlen + 1) * sizeof(char));
if (!str)
return (NULL);
str[nbrlen] = '\0';
if (ft_signe(nbr))
nbr = -nbr;
while (nbr)
{
str[--nbrlen] = nbr % 10 + 48;
nbr /= 10;
}
if (n == 0)
str[0] = n % 10 + 48;
if (ft_signe(n))
str[0] = '-';
return (str);
}