-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_itoa.c
More file actions
72 lines (66 loc) · 1.59 KB
/
ft_itoa.c
File metadata and controls
72 lines (66 loc) · 1.59 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
66
67
68
69
70
71
72
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amennad <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/10 10:47:52 by amennad #+# #+# */
/* Updated: 2023/04/21 10:20:10 by amennad ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <stdio.h>
#include <stdlib.h>
int ft_int_len(long int n)
{
int i;
i = 0;
if (!n)
return (1);
if (n < 0)
{
n = n * (-1);
i++;
}
while (n > 0)
{
i++;
n = n / 10;
}
return (i);
}
char *itoa_logic(long int n, int n_len, char *result)
{
if (n < 0)
{
result[0] = '-';
n = n * (-1);
}
while (n > 0)
{
result[n_len] = n % 10 + 48;
n = n / 10;
n_len--;
}
return (result);
}
char *ft_itoa(int n)
{
int n_len;
char *result;
long int nb;
nb = n;
n_len = ft_int_len(nb);
result = malloc(sizeof(char) * (n_len + 1));
if (!result)
return (NULL);
result[n_len--] = '\0';
if (n == 0)
{
result[0] = 48;
}
else
itoa_logic(nb, n_len, result);
return (result);
}