-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
72 lines (65 loc) · 1.58 KB
/
ft_itoa.c
File metadata and controls
72 lines (65 loc) · 1.58 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ymassiou <ymassiou@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/11/04 20:26:53 by ymassiou #+# #+# */
/* Updated: 2023/11/18 18:27:36 by ymassiou ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int nbrlen(long n)
{
int count;
count = 0;
if (n == 0)
return (1);
if (n < 0)
{
count++;
n = -n;
}
while (n)
{
count++;
n /= 10;
}
return (count);
}
static char *allocate(int len)
{
char *allocated;
allocated = NULL;
allocated = (char *)malloc(len + 1);
if (allocated == NULL)
return (NULL);
return (allocated);
}
char *ft_itoa(int n)
{
int len;
long ntmp;
char *result;
int i;
ntmp = n;
i = 0;
len = nbrlen(ntmp);
result = allocate(len);
if (result == NULL)
return (NULL);
if (ntmp < 0)
{
result[i] = '-';
i++;
ntmp = -ntmp;
}
result[len--] = 0;
while (len >= i)
{
result[len--] = (ntmp % 10) + 48;
ntmp /= 10;
}
return (result);
}