-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
73 lines (66 loc) · 1.65 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: younhwan <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/07 18:38:27 by younhwan #+# #+# */
/* Updated: 2022/07/09 13:24:01 by younhwan ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_itoa(int n);
static void convert(char *res, long nbr, size_t len);
static size_t get_num_len(long nbr);
char *ft_itoa(int n)
{
char *res;
long nbr;
size_t len;
nbr = (long) n;
len = 0;
if (nbr < 0)
{
nbr *= -1;
len++;
}
len += get_num_len(nbr);
res = (char *) malloc(sizeof(char) * (len + 1));
if (!res)
return (0);
if (n < 0)
*res = '-';
convert(res, nbr, len);
return (res);
}
static void convert(char *res, long nbr, size_t len)
{
if (!nbr)
{
*res = '0';
*(res + 1) = '\0';
return ;
}
res += len;
*res-- = '\0';
while (nbr)
{
*res-- = '0' + (nbr % 10);
nbr /= 10;
}
return ;
}
static size_t get_num_len(long nbr)
{
size_t len;
if (!nbr)
return (1);
len = 0;
while (nbr)
{
len++;
nbr /= 10;
}
return (len);
}