-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
95 lines (86 loc) · 1.98 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
87
88
89
90
91
92
93
94
95
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ysoroko <ysoroko@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/11/20 13:42:23 by ysoroko #+# #+# */
/* Updated: 2020/11/23 13:17:48 by ysoroko ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void ft_putnbr_base(unsigned int nbr, char *str, int i)
{
unsigned int n;
n = nbr;
if (n >= 10)
{
ft_putnbr_base(n / 10, str, i + 1);
ft_putnbr_base(n % 10, str, i);
}
else
{
str[i] = '0' + n;
}
}
static int ft_count_mem(int m)
{
int mem_length;
mem_length = 0;
if (m < 0)
mem_length++;
else if (m == 0)
return (1);
while (m % 10 != 0 || m / 10 != 0)
{
m = m / 10;
mem_length++;
}
return (mem_length);
}
static char *rev_str(char *str, int i)
{
int j;
char temp;
int middle;
int len;
j = 0;
len = ft_strlen(str);
middle = len / 2 + i;
while (i < middle)
{
temp = str[i];
str[i] = str[len - j - 1];
str[len - j - 1] = temp;
i++;
j++;
}
return (str);
}
char *ft_itoa(int n)
{
unsigned int m;
int mem_length;
int i;
char *str;
m = n;
i = 0;
mem_length = ft_count_mem(n);
if (!(str = malloc(sizeof(char) * (mem_length + 1))))
return (0);
if (n < 0)
{
str[0] = '-';
m *= -1;
i++;
}
str[mem_length] = '\0';
if (n == 0)
{
str[0] = '0';
return (str);
}
ft_putnbr_base(m, str, i);
return (rev_str(str, i));
}