We will develop a program to reverse a number in python using recursion. To reverse a number we need to extract the last digit of the number and add that number into a temporary variable with some calculation, then remove the last digit of the number. Do these processes until the number becomes zero.
To remove the last digit the modulus operator (%) will be helpful for us, and to remove the last digit division operator (/) can be used. To add the last digit first we need to multiply the previous value by 10. Once you get the logic, you can write the program in any language.
Example of the reverse a number:-
Number: 98456
Reverse number: 65489
Procedure to find reverse of a number,
- Take a number
- Declare a temporary variable and initialize it with 0
- Find the last digit of the number
- Multiply the temporary variable by 10
- Add that last digit to the temporary variable
- Remove the last digit of the number.
- Repeat this process from 3 to 6 until the number becomes 0.
Reverse a Number using Recursion in Python
We can use the recursion technique to reverse a number in python. A technique of defining the method/function that contains a call to itself is called recursion. We will take an integer number while declaring the variables. Then, call the function and the result will be displayed on the screen.
# Python program to reverse a number using recursion
reverse, base = 0, 1
def findReverse(num):
global reverse #function definition
global base #function definition
if(num > 0):
findReverse((int)(num/10))
reverse += (num % 10) * base
base *= 10
return reverse
# take inputs
num = 12345
# calling function and display result
print('The reverse number is =', findReverse(num))
Output:-
The reverse number is = 54321
Reverse a Number in Python using Recursion
In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.
# Python program to reverse a number using recursion
reverse, base = 0, 1
def findReverse(num):
global reverse #function definition
global base #function definition
if(num > 0):
findReverse((int)(num/10))
reverse += (num % 10) * base
base *= 10
return reverse
# take inputs
num = int(input('Enter a number: '))
# calling function and display result
print('The reverse number is =', findReverse(num))
Output for the input values test-case-1:-
Enter a number: 123
The reverse number is = 321
Output for the input values test-case-2:-
Enter a number: 3219
The reverse number is = 9123
Output for the input values test-case-3:-
Enter a number: 4564048
The reverse number is = 8404654