ft_itoa.c
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* ft_itoa.c :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: gychoi <marvin@42.fr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2022/07/11 16:48:44 by gychoi #+# #+# */ 9 /* Updated: 2022/07/12 18:14:33 by gychoi ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "libft.h" 14 15 static int find_quotient(int n) 16 { 17 int q; 18 19 q = 1; 20 if (n < 0) 21 q *= -1; 22 if (-9 <= n && n <= 9) 23 return (q); 24 q *= 10; 25 while (n / q >= 10) 26 q *= 10; 27 return (q); 28 } 29 30 static size_t get_length(int q) 31 { 32 size_t c; 33 34 c = 1; 35 if (q < 0) 36 c++; 37 while (q / 10 != 0) 38 { 39 c++; 40 q /= 10; 41 } 42 return (c); 43 } 44 45 char *ft_itoa(int n) 46 { 47 int q; 48 size_t len; 49 size_t start; 50 char *arr; 51 52 q = find_quotient(n); 53 len = get_length(q); 54 arr = malloc(sizeof(char) * len + 1); 55 if (!arr) 56 return (NULL); 57 start = 0; 58 if (n < 0) 59 { 60 arr[start] = '-'; 61 start++; 62 } 63 while (start < len) 64 { 65 arr[start] = (n / q) + '0'; 66 start++; 67 n = n % q; 68 q /= 10; 69 } 70 arr[start] = '\0'; 71 return (arr); 72 }