-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
65 lines (59 loc) · 1.55 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aisaoglu <aisaoglu@student.42kocaeli.co +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/10/28 13:41:39 by aisaoglu #+# #+# */
/* Updated: 2023/10/28 13:41:40 by aisaoglu ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int calc(int x)
{
int i;
i = 1;
while (x >= 10 || x <= -10)
{
x /= 10;
i++;
}
return (i);
}
static int num(int x)
{
if (x > 0)
return (calc(x));
else if (x < 0)
return (calc(-1 * x) + 1);
else
return (1);
}
char *ft_itoa(int n)
{
char *new;
size_t length;
int number;
number = n;
if (n == -2147483648)
return (ft_strdup("-2147483648"));
length = num(number);
new = (char *)malloc((sizeof(char) * length) + 1);
if (!new)
return (NULL);
new[length] = '\0';
if (n < 0)
{
number *= -1;
}
while (length > 0)
{
new[length - 1] = number % 10 + '0';
number /= 10;
length--;
}
if (n < 0)
new[0] = '-';
return (new);
}