Advertisement
dmilicev

reverse_integer.c

Feb 17th, 2021
1,004
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3.     reverse_integer.c
  4.  
  5. https://www.programmingsimplified.com/c/source-code/c-program-reverse-number
  6. https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/
  7.  
  8.  
  9.     You can find all my C programs at Dragan Milicev's pastebin:
  10.  
  11.     https://pastebin.com/u/dmilicev
  12.  
  13. */
  14.  
  15. #include <stdio.h>
  16.  
  17. int reverse_v1(int num)
  18. {
  19.     int rev_num = 0;
  20.  
  21.     while(num > 0)
  22.     {
  23.         rev_num = rev_num*10 + num%10;
  24.         num = num/10;
  25.     }
  26.  
  27.     return rev_num;
  28. }
  29.  
  30. int reverse_by_recursion_v1(int num, int rev)
  31. {
  32.     if(num==0)
  33.         return rev;
  34.     else
  35.         return reverse_by_recursion_v1(num/10, rev*10 + num%10);
  36. }
  37.  
  38. long reverse_by_recursion_v2(long n) {
  39.    static long r = 0;
  40.  
  41.    if (n == 0)
  42.       return 0;
  43.  
  44.    r = r * 10;
  45.    r = r + n % 10;
  46.    reverse_by_recursion_v2(n/10);
  47.  
  48.    return r;
  49. }
  50.  
  51. int main(void)
  52. {
  53.     int number, reversed_number;
  54.  
  55.     printf("\n Enter integer: ");
  56.     scanf("%d", &number);
  57.  
  58.     reversed_number = reverse_v1(number);
  59.     printf("\n\n\t reverse_v1(number) \n");
  60.     printf("\n Reverse of %d  is  %d \n", number, reversed_number);
  61.  
  62.     // reverse by recursion v1
  63.     // Second argument must be 0 while calling function
  64.     printf("\n\n\t reverse_by_recursion(number, 0) \n");
  65.     reversed_number = reverse_by_recursion_v1(number, 0);
  66.     printf("\n Reverse of %d  is  %d \n", number, reversed_number);
  67.  
  68.     // reverse by recursion v2
  69.     printf("\n\n\t reverse_by_recursion_v2(number) \n");
  70.     reversed_number = reverse_by_recursion_v2(number);
  71.     printf("\n Reverse of %d  is  %d \n\n", number, reversed_number);
  72.  
  73.     return 0;
  74.  
  75. } // main()
  76.  
Advertisement
RAW Paste Data Copied
Advertisement