-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathft_itoa.c
More file actions
63 lines (57 loc) · 1.9 KB
/
Copy pathft_itoa.c
File metadata and controls
63 lines (57 loc) · 1.9 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cado-car <cado-car@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/31 11:46:17 by cado-car #+# #+# */
/* Updated: 2021/08/02 11:19:08 by cado-car ### ########lyon.fr */
/* */
/* ************************************************************************** */
/*
* DESCRIPTION
* Allocates (with malloc) and returns a string representing the integer
* received as an argument. Negative numbers must be handled.
* PARAMETERS
* #1. the integer to convert.
* RETURN VALUES
* The string representing the integer. NULL if the allocation fails.
*/
#include "libft.h"
int ft_countsize(long int n);
void ft_convbase(long int n, char *number, long int i);
char *ft_itoa(int n)
{
char *number;
long int len;
len = ft_countsize(n);
number = (char *)malloc((len + 1) * sizeof(char));
if (!number)
return (NULL);
number[len--] = '\0';
ft_convbase(n, number, len);
return (number);
}
// recursively count integer size
int ft_countsize(long int n)
{
if (n < 0)
return (1 + ft_countsize(-n));
if ((n / 10) == 0)
return (1);
else
return (1 + ft_countsize(n / 10));
}
// recursively convert integer to string
void ft_convbase(long int n, char *number, long int i)
{
if (n < 0)
{
number[0] = '-';
n *= -1;
}
if (n >= 10)
ft_convbase((n / 10), number, (i - 1));
number[i] = (n % 10) + '0';
}