You are on page 1of 1

Reverse Number

Problem Description: ​You have given a number N, you have to reverse the given number N
recursively.
For example, N = 1234
Output = 4321

How to approach?
To reverse a number the observation we can easily make is that our last digit becomes the first
digit, last second digit becomes the second digit and so on.
To proceed with this problem recursively, we can take care of what our smaller problem should
be?
So to reverse a number N, we can get our small answer first, by making a recursive call to the
subproblem N/10, i.e. we can reverse N/10 first. Then in the small calculation part, we can
append our small answer(reverse of N/10) to the last digit. The last digit of N can be obtained by
taking remainder with 10 i.e. N%10.

The last digit is appended to the reversed number till now by multiplying the last digit with
10length of input −1 + reversed number till now. This will give you the desired number.

Pseudo Code for the problem:


Function: reverseHelper(input, length):
if(length==1):
return input
return (((input%10) * pow(10,length-1))+reverseHelper(input/10,length-1))

Function: reverse( input):


temp=input
length=find the length of input
return reverseHelper(input,length)

You might also like