-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
60 lines (54 loc) · 1.53 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: inwagner <inwagner@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/03 18:09:11 by inwagner #+# #+# */
/* Updated: 2023/06/09 15:12:51 by inwagner ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_intlen(int n)
{
if (!(n / 10))
return (1);
return (1 + ft_intlen(n / 10));
}
static int ft_isnegative(int n)
{
if (n < 0)
return (-1);
return (0);
}
char *ft_itoa(int n)
{
size_t num;
int sig;
int len;
char *str;
sig = ft_isnegative(n);
num = ft_abs(n);
len = ft_intlen(num);
if (sig)
len++;
str = (char *)ft_calloc(len + 1, sizeof(char));
if (!str)
return (0);
len--;
if (!num)
str[0] = '0';
if (sig)
str[0] = '-';
while (num)
{
str[len--] = (num % 10) + '0';
num /= 10;
}
return (str);
}
/*
Transforma o número 'n' em uma string.
Retorna a string, ou nulo se a alocação falhar.
*/