WAP to reverse of a number using recursion.
Objective
Write a C++ program to reverse a number using Recursion.
Algorithm / Approach
- Calculate the total number of digits (length) of the number.
- Call
rev(num, length). - Base Case: If
len == 1, return the number. - Recursive Step: Extract the last digit, multiply it by 10^(length-1), and add it to the recursive call of the remaining digits.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int rev(int, int);
int main() {
int num, res;
int length = 0, temp;
cout<<"Enter a number: ";
cin>>num;
temp = num;
while (temp != 0) {
length++;
temp = temp / 10;
}
res = rev(num, length);
cout<<"Reverse = "<< res<< endl;
return 0;
}
int rev(int n, int len) {
int x;
cout<< " this is x"<< n<< endl;
if (len == 1) {
return n+1;
}
else {
x = ((n % 10) * pow(10, len-1));
return ( x + rev(n / 10,--len));
}
}
Expected Output
Enter a number: 1234 Reverse = 4321
Explanation of the Program
- This applies recursion to a math problem by stripping the last digit off, shifting it all the way to the front using math (10^length-1), and recursively doing the same for the remaining digits.
- Note on the provided code: The base case returns
n + 1. This is a logical bug that will artificially inflate the final reversed number by 1!
Complexity
Time Complexity
O(log₁₀ n)
Space Complexity
O(log₁₀ n) - Call stack size equals the number of digits.
Common Mistakes
- Logical Error: The recursive base case returns
n + 1instead of justn, corrupting the final mathematical result.