-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
97 lines (87 loc) · 1.88 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: masoares <masoares@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/07 11:11:37 by masoares #+# #+# */
/* Updated: 2023/10/08 20:33:26 by masoares ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int count_digits(long n)
{
int count;
count = 0;
while (n != 0)
{
n = n / 10;
count++;
}
return (count);
}
int ft_power(int n, int pow)
{
int i;
int num;
num = n;
i = 1;
if (pow == 0)
n = 1;
while (i < pow)
{
n = n * num;
i++;
}
return (n);
}
char *write_num(long n, int d)
{
char *str;
int i;
i = 0;
if (n < 0)
d++;
str = (char *) malloc (sizeof(char) * (d + 1));
if (str == NULL)
return (NULL);
if (n < 0)
{
i = 1;
str[0] = '-';
n = n * (-1);
d--;
}
while (--d >= 0)
{
str[i++] = (n / ft_power(10, d)) + '0';
n = n - ((n / ft_power(10, d)) * ft_power(10, d));
}
str[i] = '\0';
return (str);
}
char *ft_itoa(int n)
{
int d;
char *str;
long num;
num = n;
d = count_digits(num);
if (d == 0)
{
str = (char *) malloc (sizeof(char) * 2);
if (str == NULL)
return (NULL);
str[0] = '0';
str[1] = '\0';
return (str);
}
str = write_num(num, d);
return (str);
}
/*
int main(void)
{
printf("%s\n", ft_itoa(ft_atoi("-3590")));
}*/