-
Notifications
You must be signed in to change notification settings - Fork 0
/
ft_itoa.c
69 lines (60 loc) · 1.67 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tpouget <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/05/14 17:04:37 by tpouget #+# #+# */
/* Updated: 2020/05/27 11:08:21 by tpouget ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static long ft_10powerof(long n)
{
long result;
result = 1;
while (n--)
result *= 10;
return (result);
}
char *ft_itoa(int n)
{
long nbr;
long digit;
long i;
long len;
char *result;
len = 1;
nbr = n < 0 ? -1 * (long)n : n;
i = nbr;
while (i /= 10)
len++;
result = n < 0 ? malloc(len + 2) : malloc(len + 1);
if (!result)
return (NULL);
i = 0;
if (n < 0)
result[i++] = '-';
while (--len >= 0)
{
digit = nbr / ft_10powerof(len);
result[i++] = digit + '0';
nbr = nbr - digit * ft_10powerof(len);
}
result[i] = '\0';
return (result);
}
/*
#include <stdio.h>
int main(int argc, char **argv)
{
//if (argc != 2) return 1;
// int n = atoi(argv[1]);
// int n = -2147483648;
int n = -5859;
char *result = ft_itoa(n);
printf("%s\n", result);
return 0;
}
*/