-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
67 lines (61 loc) · 1.57 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ibeliaie <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/05/19 13:25:28 by ibeliaie #+# #+# */
/* Updated: 2023/05/23 13:09:39 by ibeliaie ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
/* number of digits in int */
static int count(int n)
{
int i;
i = 0;
if (n <= 0)
i++;
while (n != 0)
{
n /= 10;
i++;
}
return (i);
}
/* convert int to str */
static char *convert(int len, int p, char *ptr, int n)
{
while (len + 1 > p)
{
if (n < 0)
ptr[len] = n % 10 * (-1) + '0';
else
ptr[len] = n % 10 + '0';
n /= 10;
len--;
}
return (ptr);
}
/* convert integer to string */
char *ft_itoa(int n)
{
char *ptr;
int len;
int position;
len = 0;
len = count(n);
ptr = (char *) malloc (len + 1);
if (!ptr)
return (NULL);
position = 0;
if (n < 0)
{
ptr[0] = '-';
position = 1;
}
ptr[len] = '\0';
len--;
return (convert(len, position, ptr, n));
}