-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
77 lines (72 loc) · 1.66 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
69
70
71
72
73
74
75
76
77
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: belkarto <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/12 10:20:24 by belkarto #+# #+# */
/* Updated: 2022/10/24 11:09:28 by belkarto ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int number_count(long int n)
{
int i;
i = 0;
if (n <= 9 && n >= 0)
return (1);
while (n > 0)
{
n /= 10;
i++;
}
return (i);
}
static void string_of_number(char *s, int i, long int n)
{
if (n >= 0)
{
while (i > 0)
{
s[i - 1] = n % 10 + 48;
n /= 10;
i--;
}
}
else
{
n *= -1;
while (i > 0)
{
s[i] = n % 10 + 48;
n /= 10;
i--;
}
s[0] = '-';
}
}
char *ft_itoa(int n)
{
char *str;
int i;
long int nbr;
nbr = n;
if (nbr < 0)
i = number_count(-nbr);
else
i = number_count(nbr);
if (n < 0)
{
str = (char *)ft_calloc((i + 2), sizeof(char));
if (!str)
return (NULL);
string_of_number(str, i, nbr);
}
else
{
str = (char *)ft_calloc((i + 1), sizeof(char));
string_of_number(str, i, nbr);
}
return (str);
}