-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
67 lines (59 loc) · 1.63 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gaaraujo <gaaraujo@student.42wolfsburg.de> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/08 21:28:38 by gaaraujo #+# #+# */
/* Updated: 2024/12/08 21:29:52 by gaaraujo ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int count_digits(int n)
{
int count;
count = 1;
while (n / 10 != 0)
{
n /= 10;
count++;
}
return (count);
}
static char digit_to_char(int n)
{
char digit;
digit = '0';
if (n < 0)
digit -= n % 10;
else
digit += n % 10;
return (digit);
}
static void fill_str(char *str, int n, int length)
{
str[length--] = '\0';
if (n < 0)
str[0] = '-';
while (n / 10 != 0)
{
str[length--] = digit_to_char(n % 10);
n /= 10;
}
str[length] = digit_to_char(n);
}
char *ft_itoa(int n)
{
int length;
int is_negative;
char *str;
is_negative = n < 0;
length = is_negative;
length += count_digits(n);
str = (char *) malloc(sizeof(char) * length + 1);
if (str == NULL)
return (NULL);
fill_str(str, n, length);
return (str);
}