Given an integer N, the task is to reverse the digits of given integer using recursion.
Examples:
Input: N = 123
Output: 321
Explanation:
The reverse of the given number is 321.Input: N = 12532
Output: 23521
Explanation:
The reverse of the given number is 23521.
Approach: Follow the steps below to solve the problem:
- Recursively iterate every digit of N.
- If the current value of N passed is less than 10, return N.
if(num < 10) Â Â Â return N;
- Otherwise, after each recursive call (except the base case), return the recursive function for next iteration:
  return reverse(N/10) + ((N%10)*(pow(10, (floor(log10(abs(N))))))) where, floor(log10(abs(x))) gives the count of digits of x ((x%10)*(pow(10, (floor(log10(abs(x))))))) places the extracted unit place digits (x%10) to their desired positions
Below is the implementation of the above approach:
C
// C program for the above approach Â
#include <math.h> #include <stdio.h> #include <stdlib.h> Â
// Function to reverse the digits of // the given integer int reverse( int N) { Â Â Â Â return ((N <= 9)) Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ? N Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â : reverse(N / 10) Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â + ((N % 10) Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â * ( pow (10, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ( floor ( log10 ( Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â abs (N))))))); } Â
// Utility function to reverse the // digits of the given integer void reverseUtil( int N) {     // Stores reversed integer     int result = reverse(N); Â
    // Print reversed integer     printf ( "%d" , result); } Â
// Driver Code int main() { Â Â Â Â // Given integer N Â Â Â Â int N = 123; Â
    // Function Call     reverseUtil(N); Â
    return 0; } |
321
Time Complexity: O(log10N)
Auxiliary Space: O(log10N) for call stack
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!