-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
83 lines (76 loc) · 1.84 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hkonte <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/11/29 13:13:55 by hkonte #+# #+# */
/* Updated: 2024/11/29 13:14:27 by hkonte ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_intsize(int n)
{
long int val;
int count;
int is_negative;
count = 0;
is_negative = n < 0;
if (is_negative)
val = -(long int)n;
else
val = (long int)n;
while (val > 0)
{
val /= 10;
count++;
}
return (1 + (n == 0) + count + is_negative);
}
static char *ft_strrev(char *str)
{
int i;
int n;
char temp;
if (!str)
return (NULL);
i = 0;
n = ft_strlen(str) - 1;
while (i < n)
{
temp = str[i];
str[i] = str[n];
str[n] = temp;
i++;
n--;
}
return (str);
}
char *ft_itoa(int n)
{
long int val;
char *result;
int is_negative;
int i;
is_negative = n < 0;
if (is_negative)
val = -(long int)n;
else
val = (long int)n;
result = ft_calloc(ft_intsize(n), sizeof(char));
if (!result)
return (NULL);
i = 0;
if (val == 0)
result[i++] = '0';
while (val > 0)
{
result[i++] = '0' + (val % 10);
val /= 10;
}
if (is_negative)
result[i++] = '-';
result[i] = '\0';
return (ft_strrev(result));
}