73 lines
1.7 KiB
C
73 lines
1.7 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* ft_itoa.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2024/10/17 17:08:01 by kcolin #+# #+# */
|
|
/* Updated: 2024/10/17 17:33:18 by kcolin ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "libft.h"
|
|
#include <stdlib.h>
|
|
|
|
static int nb_needed_chars(long num)
|
|
{
|
|
int count;
|
|
|
|
count = 0;
|
|
if (num <= 0)
|
|
{
|
|
count++;
|
|
num = -num;
|
|
}
|
|
while (num != 0)
|
|
{
|
|
count++;
|
|
num /= 10;
|
|
}
|
|
return (count);
|
|
}
|
|
|
|
char *ft_itoa(int n)
|
|
{
|
|
long num;
|
|
size_t idx;
|
|
char *out;
|
|
|
|
num = n;
|
|
idx = nb_needed_chars(num);
|
|
if (num < 0)
|
|
num = -num;
|
|
out = malloc(idx + 1);
|
|
if (out == NULL)
|
|
return (NULL);
|
|
out[idx--] = '\0';
|
|
while (num > 0)
|
|
{
|
|
out[idx--] = (num % 10) + '0';
|
|
num /= 10;
|
|
}
|
|
if (n < 0)
|
|
out[idx] = '-';
|
|
if (n == 0)
|
|
out[idx] = '0';
|
|
return (out);
|
|
}
|
|
|
|
/*
|
|
#include <stdio.h>
|
|
#include <limits.h>
|
|
|
|
int main(void)
|
|
{
|
|
printf("%s\n", ft_itoa(0));
|
|
printf("%s\n", ft_itoa(42));
|
|
printf("%s\n", ft_itoa(-42));
|
|
printf("%s\n", ft_itoa(INT_MAX));
|
|
printf("%s\n", ft_itoa(INT_MIN));
|
|
return (0);
|
|
}
|
|
*/
|