-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
116 lines (105 loc) · 2.25 KB
/
ft_itoa.c
File metadata and controls
116 lines (105 loc) · 2.25 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: sunko <sunko@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/16 13:36:30 by sunko #+# #+# */
/* Updated: 2023/04/11 12:18:50 by sunko ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
#include <stdlib.h>
unsigned int unsingend_cnt(unsigned int n)
{
int cnt;
cnt = 0;
while (n)
{
n = n / 10;
cnt++;
}
return (cnt);
}
int num_cnt(int n)
{
int cnt;
cnt = 0;
if (n < 0)
cnt++;
while (n)
{
n = n / 10;
cnt++;
}
return (cnt);
}
char *ft_negative(int n)
{
int size;
char *string;
long long tmp;
size = num_cnt(n);
string = (char *)malloc(sizeof(char) * (size + 1));
if (!string)
return (NULL);
string[0] = '-';
string[size] = '\0';
tmp = n;
tmp *= -1;
while (tmp)
{
if (size == 1)
break ;
string[--size] = tmp % 10 + '0';
tmp = tmp / 10;
}
return (string);
}
char *ft_itoa(int n)
{
int size;
char *string;
if (n < 0)
return (ft_negative(n));
size = num_cnt(n);
if (n == 0)
size = 1;
string = (char *)malloc(sizeof(char) * (size + 1));
if (!string)
return (NULL);
if (n == 0)
string[0] = '0';
string[size] = '\0';
while (n)
{
if (size == 0)
break ;
string[--size] = n % 10 + '0';
n = n / 10;
}
return (string);
}
char *ft_unsigned_itoa(unsigned int n)
{
unsigned int size;
char *string;
size = unsingend_cnt(n);
if (n == 0)
size = 1;
string = (char *)malloc(sizeof(char) * (size + 1));
if (!string)
return (NULL);
if (n == 0)
string[0] = '0';
string[size] = '\0';
while (n)
{
if (size == 0)
break ;
string[--size] = n % 10 + '0';
n = n / 10;
}
return (string);
}