-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
62 lines (57 loc) · 1.54 KB
/
ft_itoa.c
File metadata and controls
62 lines (57 loc) · 1.54 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: andcardo <andcardo@student.42lisboa.c +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/05/08 11:40:13 by andcardo #+# #+# */
/* Updated: 2025/11/29 23:38:40 by andcardo ### ########.fr */
/* */
/* ************************************************************************** */
#include "so_long.h"
static void fill_str_backwards(char *s, long nb, int index)
{
while (nb > 0)
{
s[index--] = nb % 10 + '0';
nb /= 10;
}
}
static int find_nb_of_digits(long n)
{
int digit_nb;
digit_nb = 1;
if (n < 0)
{
digit_nb += 1;
n *= -1;
}
while (n > 9)
{
digit_nb ++;
n /= 10;
}
return (digit_nb);
}
char *ft_itoa(int n)
{
int digit_nb;
long nb;
char *str;
nb = (long)n;
digit_nb = find_nb_of_digits(nb);
str = (char *)malloc((digit_nb + 1) * sizeof(char));
if (!str)
return (NULL);
str[digit_nb--] = '\0';
if (nb == 0)
str[0] = '0';
if (nb < 0)
{
str[0] = '-';
nb *= -1;
}
fill_str_backwards(str, nb, digit_nb);
return (str);
}