From 9901cd05849fa0ef396f09f57b07807ebd96ca32 Mon Sep 17 00:00:00 2001 From: Charles Date: Wed, 20 Nov 2019 04:04:55 +0100 Subject: refactored everything --- ft_itoa.c | 47 +++++++++++------------------------------------ 1 file changed, 11 insertions(+), 36 deletions(-) (limited to 'ft_itoa.c') diff --git a/ft_itoa.c b/ft_itoa.c index 03d794b..166e278 100644 --- a/ft_itoa.c +++ b/ft_itoa.c @@ -6,59 +6,34 @@ /* By: cacharle +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/07 10:19:56 by cacharle #+# #+# */ -/* Updated: 2019/11/20 01:15:40 by cacharle ### ########.fr */ +/* Updated: 2019/11/20 03:13:10 by cacharle ### ########.fr */ /* */ /* ************************************************************************** */ -#include +#include "libft.h" -static int count_len(int nbr) +char *ft_itoa(int n) { - int counter; + char *str; + int len; unsigned int u_nbr; - if (nbr == 0) - return (1); - counter = 0; - u_nbr = nbr; - if (nbr < 0) - { - counter++; - u_nbr = -nbr; - } + len = n < 0 || n == 0 ? 1 : 0; + u_nbr = n < 0 ? -n : n; while (u_nbr > 0) { u_nbr /= 10; - counter++; + len++; } - return (counter); -} - -char *ft_itoa(int n) -{ - char *str; - int len; - int is_negative; - unsigned int u_nbr; - - len = count_len(n); - if ((str = (char*)malloc(sizeof(char) * (len + 1))) == NULL) + if ((str = ft_strnew(len)) == NULL) return (NULL); - str[len] = '\0'; - is_negative = 0; - u_nbr = n; + u_nbr = n < 0 ? -n : n; if (n < 0) - { - is_negative = 1; str[0] = '-'; - u_nbr = -n; - } - len--; - while (len >= (is_negative ? 1 : 0)) + while (--len >= (n < 0 ? 1 : 0)) { str[len] = (u_nbr % 10) | 0x30; u_nbr /= 10; - len--; } return (str); } -- cgit