/04/4-4-ft_itoa/ft_itoa.c
https://github.com/fwuensche/42-exam-miner · C · 70 lines · 61 code · 9 blank · 0 comment · 13 complexity · 9272eb84131ca2bf74df90fc802df32b MD5 · raw file
- #include <stdlib.h>
- #include <stdio.h> //for main test
- static int ft_strlen(const char *s)
- {
- int i;
- i = 0;
- while (s[i])
- i++;
- return i;
- }
- static char *ft_strrev(char *str)
- {
- int i;
- int j;
- int tmp;
- i = 0;
- j = ft_strlen(str);
- while (j > i)
- {
- j--;
- tmp = str[i];
- str[i] = str[j];
- str[j] = tmp;
- i++;
- }
- return str;
- }
- char *ft_itoa(int nbr)
- {
- int i;
- int neg;
- char *tmp;
- i = 0;
- neg = 0;
- tmp = malloc(sizeof(char) * 12);
- if (tmp == NULL || nbr == 0)
- return ((nbr == 0) ? "0" : NULL);
- if (nbr == -2147483648)
- return ("-2147483648");
- if (nbr < 0)
- {
- neg = 1;
- nbr *= -1;
- }
- while (nbr)
- {
- tmp[i++] = (nbr % 10) + '0';
- nbr /= 10;
- }
- if (neg)
- tmp[i] = '-';
- return ft_strrev(tmp);
- }
- int main(void)
- {
- int i = 0;
- int tab[5] = {-2147483648, -42, 0, 42, 2147483647};
- while (i < 5)
- printf("%s\n", ft_itoa(tab[i++]));
- return 0;
- }