60 lines
1.5 KiB
C
60 lines
1.5 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_itoa.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2022/10/04 17:12:52 by erey-bet #+# #+# */
|
|
/* Updated: 2023/03/26 20:17:58 by erey-bet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "utils.h"
|
|
|
|
static long long abso(long long n)
|
|
{
|
|
if (n < 0)
|
|
return (n * -1);
|
|
return (n);
|
|
}
|
|
|
|
static void get_size(long long n, long long *q, long long *i)
|
|
{
|
|
*q = 1;
|
|
*i = 1;
|
|
while (n / *q > 9)
|
|
{
|
|
*q = *q * 10;
|
|
(*i)++;
|
|
}
|
|
}
|
|
|
|
char *ft_itoa(long long n)
|
|
{
|
|
char *str;
|
|
int sign;
|
|
long long q;
|
|
long long i;
|
|
|
|
sign = 1;
|
|
if (n < 0)
|
|
sign = -1;
|
|
n = abso(n);
|
|
get_size(n, &q, &i);
|
|
str = malloc(sizeof(char) * (i + 2));
|
|
if (!str)
|
|
return (NULL);
|
|
i = 0;
|
|
if (sign == -1)
|
|
str[i++] = '-';
|
|
while (q > 1)
|
|
{
|
|
str[i++] = (n / q % 10) + 48;
|
|
q = q / 10;
|
|
}
|
|
str[i++] = (n / q % 10) + 48;
|
|
str[i] = '\0';
|
|
return (str);
|
|
}
|