-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
92 lines (83 loc) · 1.85 KB
/
ft_itoa.c
File metadata and controls
92 lines (83 loc) · 1.85 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: marvin <marvin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/11/14 19:47:55 by marvin #+# #+# */
/* Updated: 2025/11/14 19:47:55 by marvin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_rev(char *str)
{
int i;
int len;
char temp;
len = 0;
while (str[len])
len++;
i = 0;
while (i < len / 2)
{
temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
i++;
}
}
static int ft_numlen(int n)
{
int len;
unsigned int x;
len = 0;
if (n == 0)
return (1);
if (n < 0)
x = -n;
else
x = n;
while (x > 0)
{
len++;
x = x / 10;
}
return (len);
}
static void fill_digits(char *p, unsigned int x, int is_negative)
{
int i;
i = 0;
while (x > 0)
{
p[i++] = x % 10 + '0';
x = x / 10;
}
if (is_negative)
p[i++] = '-';
p[i] = '\0';
ft_rev(p);
}
char *ft_itoa(int n)
{
int is_negative;
unsigned int x;
int len;
char *p;
if (n == 0)
return (ft_strdup("0"));
is_negative = 0;
if (n < 0)
is_negative = 1;
len = ft_numlen(n);
p = malloc(sizeof(char) * (len + is_negative + 1));
if (!p)
return (NULL);
if (n < 0)
x = -n;
else
x = n;
fill_digits(p, x, is_negative);
return (p);
}