-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
77 lines (70 loc) · 2.01 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: marvin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/24 18:53:27 by mbrito-p #+# #+# */
/* Updated: 2023/05/13 03:42:24 by marvin ### ########.fr */
/* */
/* ************************************************************************** */
// Allocates (with malloc(3)) and returns a string
// representing the integer received as an argument.
// Negative numbers must be handled.
#include "libft.h"
static char *ft_char(char *s, unsigned int number, long int len)
{
while (number > 0)
{
s[len--] = 48 + (number % 10);
number = number / 10;
}
return (s);
}
static long int ft_len(int n)
{
int len;
len = 0;
if (n <= 0)
len = 1;
while (n != 0)
{
len++;
n = n / 10;
}
return (len);
}
char *ft_itoa(int n)
{
char *s;
long int len;
unsigned int number;
int sign;
sign = 1;
len = ft_len(n);
s = (char *)malloc(sizeof(char) * (len + 1));
if (!(s))
return (0);
s[len--] = '\0';
if (n == 0)
s[0] = '0';
if (n < 0)
{
sign *= -1;
number = n * -1;
s[0] = '-';
}
else
number = n;
s = ft_char(s, number, len);
return (s);
}
// int main(void)
// {
// int number;
// char s;
// s = ft_itoa(-119);
// printf("itoa:%s",s);
// return (0);
// }