-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
86 lines (77 loc) · 1.75 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
83
84
85
86
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adbouras <adbouras@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/16 10:29:08 by adbouras #+# #+# */
/* Updated: 2023/12/20 17:55:10 by adbouras ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_sign(int n)
{
int sign;
sign = 0;
if (n < 0)
sign = 1;
return (sign);
}
static int ft_nlen(long n)
{
int i;
i = 0;
if (n == 0)
return (1);
while (n > 0)
{
n = n / 10;
i++;
}
return (i);
}
static char *ft_rev_swap(char *str)
{
char swap;
int i;
int j;
i = 0;
j = ft_strlen(str) - 1;
while (i < j)
{
swap = str[i];
str[i] = str[j];
str[j] = swap;
i++;
j--;
}
return (str);
}
char *ft_itoa(int n)
{
char *str;
int sign;
int len;
int i;
long long_n;
long_n = n;
if (long_n < 0)
long_n = long_n * (-1);
sign = ft_sign(n);
len = ft_nlen(long_n);
str = ft_calloc((len + sign + 1), sizeof(char));
if (str == NULL)
return (NULL);
i = 0;
while (long_n > 0)
{
str[i++] = long_n % 10 + '0';
long_n = long_n / 10;
}
if (sign == 1)
str[i] = '-';
if (i == 0)
str[i] = '0';
return (ft_rev_swap(str));
}