-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
71 lines (64 loc) · 1.81 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: anarodri <anarodri@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/14 11:19:03 by anarodri #+# #+# */
/* Updated: 2022/12/15 12:51:09 by anarodri ### ########.fr */
/* */
/* ************************************************************************** */
/* Allocates (with malloc(3)) and returns a string representing the integer n
** received as an argument. Negative numbers must be handled.
** Return: The string representing the integer n. NULL if the allocation fails.
** Ex: Input: int = 123 | Output: char *str = "123"
*/
#include "../libft.h"
static int ft_count_digits(int nb)
{
long int count;
count = 1;
if (nb < 0)
{
count++;
nb *= -1;
}
while (nb >= 10)
{
count++;
nb /= 10;
}
return (count);
}
static char *ft_putzero(char *str)
{
str[0] = '0';
str[1] = '\0';
return (str);
}
char *ft_itoa(int n)
{
char *str;
long int len;
len = ft_count_digits(n);
if (n == -2147483648)
return (ft_strdup("-2147483648"));
str = (char *)malloc(sizeof(char) * len + 1);
if (str == NULL)
return (NULL);
str[len--] = '\0';
if (n < 0)
{
str[0] = '-';
n *= -1;
}
if (n == 0)
ft_putzero(str);
while (n > 0)
{
str[len--] = (n % 10) + '0';
n /= 10;
}
return (str);
}