/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

  1. #include <stdlib.h>
  2. #include <stdio.h> //for main test
  3. static int ft_strlen(const char *s)
  4. {
  5. int i;
  6. i = 0;
  7. while (s[i])
  8. i++;
  9. return i;
  10. }
  11. static char *ft_strrev(char *str)
  12. {
  13. int i;
  14. int j;
  15. int tmp;
  16. i = 0;
  17. j = ft_strlen(str);
  18. while (j > i)
  19. {
  20. j--;
  21. tmp = str[i];
  22. str[i] = str[j];
  23. str[j] = tmp;
  24. i++;
  25. }
  26. return str;
  27. }
  28. char *ft_itoa(int nbr)
  29. {
  30. int i;
  31. int neg;
  32. char *tmp;
  33. i = 0;
  34. neg = 0;
  35. tmp = malloc(sizeof(char) * 12);
  36. if (tmp == NULL || nbr == 0)
  37. return ((nbr == 0) ? "0" : NULL);
  38. if (nbr == -2147483648)
  39. return ("-2147483648");
  40. if (nbr < 0)
  41. {
  42. neg = 1;
  43. nbr *= -1;
  44. }
  45. while (nbr)
  46. {
  47. tmp[i++] = (nbr % 10) + '0';
  48. nbr /= 10;
  49. }
  50. if (neg)
  51. tmp[i] = '-';
  52. return ft_strrev(tmp);
  53. }
  54. int main(void)
  55. {
  56. int i = 0;
  57. int tab[5] = {-2147483648, -42, 0, 42, 2147483647};
  58. while (i < 5)
  59. printf("%s\n", ft_itoa(tab[i++]));
  60. return 0;
  61. }