-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
64 lines (58 loc) · 1.61 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jonchoi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/12 23:54:18 by jonchoi #+# #+# */
/* Updated: 2022/07/19 23:46:06 by jonchoi ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static char *ft_cutnum(unsigned int num, size_t *size)
{
char *result;
result = (char *)malloc(sizeof(char) * (*size + 1));
if (!result)
return (0);
result[*size] = '\0';
while (num)
{
result[*size - 1] = num % 10 + '0';
num /= 10;
(*size)--;
}
return (result);
}
static size_t *size_check(int n, size_t *size)
{
while (n)
{
n /= 10;
(*size)++;
}
return (size);
}
char *ft_itoa(int n)
{
size_t size;
char *result;
unsigned int num;
size = 0;
num = 0;
if (n > 0)
num = n;
else if (n <= 0)
{
num = -n;
size += 1;
}
size = *size_check(n, &size);
result = ft_cutnum(num, &size);
if (num == 0)
result[0] = '0';
else if (size == 1 && result[1] != '\0')
result[0] = '-';
return (result);
}