-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
58 lines (54 loc) · 1.4 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: macelik <macelik@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/15 12:27:04 by macelik #+# #+# */
/* Updated: 2023/02/15 12:41:28 by macelik ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int length(int nb)
{
int s;
if (nb == 0)
return (1);
s = 0;
if (nb < 0)
s = 1;
while (nb)
{
s++;
nb = nb / 10;
}
return (s);
}
char *ft_itoa(int n)
{
char *str;
int len;
unsigned int num;
len = length(n);
str = (char *)malloc(sizeof(char) * (len + 1));
if (!str)
return (NULL);
str[len] = '\0';
len--;
str[len] = '0';
if (n < 0)
{
str[0] = '-';
num = -n;
}
else
num = n;
while (num)
{
str[len] = ('0' + (num % 10));
num = num / 10;
len--;
}
return (str);
}