78 lines
1.7 KiB
C
78 lines
1.7 KiB
C
|
|
/* ************************************************************************** */
|
||
|
|
/* */
|
||
|
|
/* ::: :::::::: */
|
||
|
|
/* ft_itoa.c :+: :+: :+: */
|
||
|
|
/* +:+ +:+ +:+ */
|
||
|
|
/* By: gbaconni <gbaconni@42lausanne.ch> +#+ +:+ +#+ */
|
||
|
|
/* +#+#+#+#+#+ +#+ */
|
||
|
|
/* Created: 2021/10/11 14:33:40 by gbaconni #+# #+# */
|
||
|
|
/* Updated: 2021/10/23 16:23:10 by gbaconni ### ########.fr */
|
||
|
|
/* */
|
||
|
|
/* ************************************************************************** */
|
||
|
|
|
||
|
|
#include "libft.h"
|
||
|
|
|
||
|
|
static int ft_intlen(int n);
|
||
|
|
static char *ft_strrev(char *s);
|
||
|
|
|
||
|
|
char *ft_itoa(int n)
|
||
|
|
{
|
||
|
|
char *s;
|
||
|
|
int i;
|
||
|
|
long nbr;
|
||
|
|
|
||
|
|
s = (char *) ft_calloc((ft_intlen(n) + 1), sizeof(char));
|
||
|
|
if (s == NULL)
|
||
|
|
return (NULL);
|
||
|
|
i = 0;
|
||
|
|
nbr = n;
|
||
|
|
if (nbr == 0)
|
||
|
|
s[i++] = '0';
|
||
|
|
if (nbr < 0)
|
||
|
|
nbr = -nbr;
|
||
|
|
while (nbr > 0)
|
||
|
|
{
|
||
|
|
s[i++] = '0' + nbr % 10;
|
||
|
|
nbr /= 10;
|
||
|
|
}
|
||
|
|
if (n < 0)
|
||
|
|
s[i++] = '-';
|
||
|
|
s[i] = '\0';
|
||
|
|
return (ft_strrev(s));
|
||
|
|
}
|
||
|
|
|
||
|
|
static int ft_intlen(int n)
|
||
|
|
{
|
||
|
|
size_t len;
|
||
|
|
|
||
|
|
len = 0;
|
||
|
|
if (n < 0 || n == 0)
|
||
|
|
len++;
|
||
|
|
while (!(n < 1 && n > -1))
|
||
|
|
{
|
||
|
|
n /= 10;
|
||
|
|
len++;
|
||
|
|
}
|
||
|
|
return (len);
|
||
|
|
}
|
||
|
|
|
||
|
|
static char *ft_strrev(char *s)
|
||
|
|
{
|
||
|
|
int len;
|
||
|
|
int i;
|
||
|
|
int j;
|
||
|
|
char c;
|
||
|
|
|
||
|
|
len = ft_strlen(s);
|
||
|
|
i = 0;
|
||
|
|
while (i < (len / 2))
|
||
|
|
{
|
||
|
|
j = len - 1 - i;
|
||
|
|
c = s[i];
|
||
|
|
s[i] = s[j];
|
||
|
|
s[j] = c;
|
||
|
|
i++;
|
||
|
|
}
|
||
|
|
return (s);
|
||
|
|
}
|