-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
executable file
·72 lines (63 loc) · 1.71 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jchoy-me <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/07/11 14:30:19 by jchoy-me #+# #+# */
/* Updated: 2023/07/17 16:32:16 by jchoy-me ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/*
DESCRIPTION:
Allocates (with malloc(3)) and returns a string representing the integer
received as an argument. Negative numbers must be handled.
PARAMETERS:
n: the integer to convert.
RETURN VALUE:
The string representing the integer.
NULL if the allocation fails.
EXTERNAL FUNCTIONS:
malloc
*/
static int ft_get_size(int nb)
{
int len;
len = 0;
if (nb <= 0)
len++;
while (nb != 0)
{
nb = nb / 10;
len++;
}
return (len);
}
char *ft_itoa(int n)
{
char *str;
int size;
unsigned int nbr;
size = ft_get_size(n);
str = (char *) malloc(sizeof(char) * (size + 1));
if (str == NULL)
return (NULL);
nbr = n;
if (n < 0)
{
str[0] = '-';
nbr = n * (-1);
}
if (nbr == 0)
str[0] = '0';
str[size] = '\0';
while (nbr != 0)
{
size--;
str[size] = (nbr % 10) + '0';
nbr = nbr / 10;
}
return (str);
}