-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathft_itoa.c
executable file
·54 lines (49 loc) · 1.42 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: zskeeter <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/25 13:54:05 by zskeeter #+# #+# */
/* Updated: 2021/04/25 13:54:05 by zskeeter ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
int count_digits(long n)
{
int counter;
if (n == 0)
return (1);
counter = 0;
while (n != 0)
{
n /= 10;
counter++;
}
return (counter);
}
char *ft_itoa(int n)
{
char *res;
int len;
int pos;
long num;
num = n;
pos = num >= 0;
len = count_digits(num) + (!pos ? 1 : 0);
num *= pos ? 1 : -1;
if (!(res = malloc(sizeof(char) * (len + 1))))
return (NULL);
res[len] = '\0';
while (len >= 0)
{
res[len - 1] = num % 10 + 48;
num /= 10;
len--;
}
if (!pos)
res[0] = '-';
return (res);
}