-
Notifications
You must be signed in to change notification settings - Fork 1
/
ft_itoa.c
82 lines (73 loc) · 1.94 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
/* ************************************************************************** */
/* */
/* :::::::: */
/* ft_itoa.c :+: :+: */
/* +:+ */
/* By: ksmorozo <ksmorozo@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/11/04 12:21:46 by ksmorozo #+# #+# */
/* Updated: 2021/07/07 12:16:11 by ksmorozo ######## odam.nl */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdlib.h>
static int count_int_length(int n)
{
int length;
length = 0;
if (n == 0)
return (1);
while (n > 0)
{
n = n / 10;
length++;
}
return (length);
}
static int copy_digit(int n, int length, char *dest)
{
char digit;
digit = (n % 10) + '0';
dest[length - 1] = digit;
n = n / 10;
return (n);
}
static void is_negative_number(int *is_negative_num, int n)
{
if (n < 0)
*is_negative_num = 1;
else
*is_negative_num = 0;
}
static char *copy(int n)
{
char *dest;
int count;
int length;
int is_negative_num;
count = 0;
is_negative_number(&is_negative_num, n);
if (n < 0)
n = n * -1;
length = count_int_length(n);
dest = (char *)malloc(length + is_negative_num + 1);
if (dest == NULL)
return (NULL);
length += is_negative_num;
dest[length] = '\0';
while (length > (0 + is_negative_num))
{
n = copy_digit(n, length, dest);
count++;
length--;
}
if (is_negative_num == 1)
dest[0] = '-';
return (dest);
}
char *ft_itoa(int n)
{
if (n == -2147483648)
return (ft_strdup("-2147483648"));
return (copy(n));
}