-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
76 lines (70 loc) · 1.61 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ttavares <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/10 13:51:37 by ttavares #+# #+# */
/* Updated: 2022/12/06 11:02:08 by ttavares ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
static int ft_nbrsize(int n)
{
int size;
size = 0;
if (n == -2147483648)
return (11);
if (n < 0)
{
n *= -1;
size++;
}
if (n == 0)
size++;
while (n > 0)
{
n = n / 10;
size++;
}
return (size);
}
static int ft_nbrflip(int n)
{
if (n == -2147483648)
{
n++;
n *= -1;
}
else if (n < 0)
n *= -1;
return (n);
}
char *ft_itoa(int n)
{
char *ptr;
int size;
int nbr;
int i;
size = ft_nbrsize(n);
ptr = (char *)malloc(size + 1);
if (!ptr)
return (0);
nbr = ft_nbrflip(n);
i = size - 1;
ptr[size] = '\0';
while (nbr > 0)
{
ptr[i] = nbr % 10 + '0';
nbr /= 10;
i--;
}
if (n == -2147483648)
ptr[10] = '8';
if (n == 0)
ptr[0] = '0';
if (n < 0)
ptr[0] = '-';
return (ptr);
}