2022-09-27 11:25:41 -04:00
|
|
|
/* ************************************************************************** */
|
|
|
|
/* */
|
|
|
|
/* ::: :::::::: */
|
2022-10-04 08:21:55 -04:00
|
|
|
/* ft_itoa.c :+: :+: :+: */
|
2022-09-27 11:25:41 -04:00
|
|
|
/* +:+ +:+ +:+ */
|
|
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
|
|
/* +#+#+#+#+#+ +#+ */
|
2022-10-04 08:21:55 -04:00
|
|
|
/* Created: 2022/09/29 13:49:45 by cchauvet #+# #+# */
|
|
|
|
/* Updated: 2022/09/29 18:07:15 by cchauvet ### ########.fr */
|
2022-09-27 11:25:41 -04:00
|
|
|
/* */
|
|
|
|
/* ************************************************************************** */
|
|
|
|
|
|
|
|
#include "libft.h"
|
|
|
|
|
2022-10-04 08:21:55 -04:00
|
|
|
static int ft_nb_digit(int n)
|
2022-09-27 11:25:41 -04:00
|
|
|
{
|
2022-10-04 08:21:55 -04:00
|
|
|
int out;
|
2022-09-27 11:25:41 -04:00
|
|
|
|
2022-10-04 08:21:55 -04:00
|
|
|
out = 0;
|
|
|
|
while (n)
|
|
|
|
{
|
|
|
|
n /= 10;
|
|
|
|
out++;
|
|
|
|
}
|
|
|
|
return (out);
|
|
|
|
}
|
|
|
|
|
|
|
|
char *ft_itoa(int n)
|
|
|
|
{
|
|
|
|
char *out;
|
|
|
|
unsigned int nb[2];
|
|
|
|
|
|
|
|
if (!n)
|
|
|
|
return (ft_strdup("0"));
|
|
|
|
nb[0] = ft_nb_digit(n);
|
|
|
|
if (n < 0)
|
|
|
|
{
|
|
|
|
nb[1] = -n;
|
|
|
|
nb[0]++;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
nb[1] = n;
|
|
|
|
out = malloc(sizeof(char) * (nb[0] + 1));
|
|
|
|
if (out == NULL)
|
|
|
|
return (NULL);
|
|
|
|
out[nb[0]--] = 0;
|
|
|
|
if (n < 0)
|
|
|
|
out[0] = '-';
|
|
|
|
while (nb[1])
|
|
|
|
{
|
|
|
|
out[nb[0]--] = nb[1] % 10 + 48;
|
|
|
|
nb[1] /= 10;
|
|
|
|
}
|
|
|
|
return (out);
|
2022-09-27 11:25:41 -04:00
|
|
|
}
|