diff options
| author | Charles <sircharlesaze@gmail.com> | 2019-11-20 04:04:55 +0100 |
|---|---|---|
| committer | Charles <sircharlesaze@gmail.com> | 2019-11-20 04:04:55 +0100 |
| commit | 9901cd05849fa0ef396f09f57b07807ebd96ca32 (patch) | |
| tree | f2dd9c191512bfc11c994e578291cccf270de787 /ft_itoa.c | |
| parent | a983b06df18647cf63fadad5b36f472e06f1075f (diff) | |
| download | libft-9901cd05849fa0ef396f09f57b07807ebd96ca32.tar.gz libft-9901cd05849fa0ef396f09f57b07807ebd96ca32.tar.bz2 libft-9901cd05849fa0ef396f09f57b07807ebd96ca32.zip | |
refactored everything
Diffstat (limited to 'ft_itoa.c')
| -rw-r--r-- | ft_itoa.c | 47 |
1 files changed, 11 insertions, 36 deletions
@@ -6,59 +6,34 @@ /* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* 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 <stdlib.h> +#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); } |
