C Program to reverse the digits of a number using recursion
Input: N = 123
The reverse of the given number is 321.
Input: N = 12532
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)
- 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:
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.