-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
74 lines (68 loc) · 1.57 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dvan-der <dvan-der@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/15 08:22:47 by dvan-der #+# #+# */
/* Updated: 2021/12/15 08:22:55 by dvan-der ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int nbr_len(long long n, int p_n)
{
int i;
i = 0;
if (n == 0)
i++;
while (n > 0)
{
n = n / 10;
i++;
}
if (p_n)
i++;
return (i);
}
static char *make_str(long long n, char *str, int i, int p_n)
{
str[i] = '\0';
i--;
if (n == 0)
{
str[i] = '0';
i--;
}
while (n > 0)
{
str[i] = (n % 10) + '0';
i--;
n = n / 10;
}
if (p_n)
{
str[i] = '-';
i++;
}
return (str);
}
char *ft_itoa(int n)
{
int i;
int p_n;
char *str;
long long x;
p_n = 0;
x = (long long)n;
if (n < 0)
{
p_n = 1;
x *= -1;
}
i = nbr_len(x, p_n);
str = malloc(i * sizeof(char) + 1);
ft_check_malloc(str, "ft_itoa");
str = make_str(x, str, i, p_n);
return (str);
}