-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
73 lines (66 loc) · 1.64 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mmasuda <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/11 22:30:20 by mmasuda #+# #+# */
/* Updated: 2021/04/18 23:40:56 by mmasuda ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int check_num(long num, int *minus)
{
int digit;
digit = 0;
if (num == 0)
digit++;
if (num < 0)
{
num *= -1;
*minus = 1;
digit++;
}
while (num > 0)
{
num /= 10;
digit++;
}
return (digit);
}
static char *calc_itoa(long num, int minus, int digit)
{
int i;
char *str;
i = 0;
str = (char *)malloc((sizeof(char) * (digit + 1)));
if (!str)
return (NULL);
if (minus)
{
str[0] = '-';
num *= -1;
}
if (num == 0)
str[0] = '0';
while (num > 0)
{
str[digit - i - 1] = num % 10 + '0';
num /= 10;
i++;
}
str[digit] = '\0';
return (str);
}
char *ft_itoa(int n)
{
long num;
int digit;
int minus;
num = (long)n;
digit = 0;
minus = 0;
digit = check_num(num, &minus);
return (calc_itoa(num, minus, digit));
}