-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
65 lines (60 loc) · 1.48 KB
/
ft_itoa.c
File metadata and controls
65 lines (60 loc) · 1.48 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ychihab <ychihab@student.1337.ma> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/10/06 11:36:34 by ychihab #+# #+# */
/* Updated: 2022/10/24 08:15:47 by ychihab ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int ft_count_int(int n)
{
int i;
unsigned int nbr;
i = 0;
if (n == 0)
i = 1;
if (n < 0)
{
nbr = n * -1;
i = 1;
}
else
nbr = n;
while (nbr)
{
nbr = nbr / 10;
i++;
}
return (i);
}
char *ft_itoa(int n)
{
char *ptr;
int size;
unsigned int nbr;
size = ft_count_int(n);
ptr = malloc((size + 1) * sizeof(char));
if (ptr == NULL)
return (0);
ptr[size] = '\0';
if (n == 0)
ptr[0] = n + '0';
if (n < 0)
{
ptr[0] = '-';
nbr = n * -1;
}
else
nbr = n;
while (nbr)
{
ptr[size - 1] = nbr % 10 + '0';
nbr = nbr / 10;
size--;
}
return (ptr);
}