Table of Contents
Top 4 Way to Find Reverse a Number in Python
Algorithm
Using While Loop
Using String slicing
Using Recursion
Algorithm
#Write the Algorithm to find the reverse of number.
- Start
- Let the number be x, Variable a for Reminder,r for result
- Initialize variable r=0
- Condition (x!=0)
- a=x%10
- r=r*10+a
- x=x/10 goto Step 4
- Display Result r
- Stop
Using While Loop
#Program to find Reverse Numbers using Using While loop
r=0
print("Enter the number")
n=int(input())
while n!=0:
a = n% 10
r=r * 10 + a
n=n//10
print("Reversed Number is: ",r)
Output:
Enter the number 567
Reversed Number is: 765
Reversed Number is: 765
Using String slicing
#Program to find Reverse Numbers using Using String slicing
print("Enter the number")
n=input()
print(str(n)[::-1])
Using Recursion
#Reverse a Number Using Recursion
n= int(input("Enter the Choice"))
r=0
def reverse(n):
global r # We can use it out of the function
if (n > 0):
a= n % 10
r= (r* 10) + a
reverse(n // 10)
return r
r= reverse(n)
print("Reverse of entered number is =",r)