-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
71 lines (66 loc) · 1.62 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: vcodrean <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/22 15:14:45 by vcodrean #+# #+# */
/* Updated: 2022/10/01 10:08:49 by vcodrean ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/**
* The above function converts an integer to a string.
*
* param int num the number to be converted to a string
*
* return A string of the number.
*/
static int count_char(int num)
{
int count;
count = 0;
if (num != 0)
{
if (num < 0)
{
num = num *(-1);
count++;
}
while (num != 0)
{
num = num / 10;
count++;
}
}
else
count = 1;
return (count);
}
char *ft_itoa(int n)
{
int len;
char *str;
long int nbr;
len = count_char(n);
nbr = n;
str = malloc(sizeof(char) * (len + 1));
if (!str)
return (0);
if (nbr < 0)
{
str[0] = '-';
nbr = -nbr;
}
if (nbr == 0)
str[0] = '0';
str[len--] = '\0';
while (nbr)
{
str[len] = ((nbr % 10) + '0');
nbr /= 10;
len--;
}
return (str);
}