In this tutorial, we will learn how to reverse a number in python.
Explanation ✏
- First of all, let's take input from the user for eg 1326
- Then we need to use a while loop and set the value of n > 0, which means the while loop run until the value of n is not equal to 0.
- Then r = n % 10 means if the number is 1326 then it first prints the last number 6 then 2, 3, and at last 1.
- After that rev = (rev * 10) +r means at first the value is 6, then 62, 623, and 6231 (please set the value of rev = 0 at first)
- Then finally n = n // 10 it means at first the value of n is 132 ( it removes the last digit then 13, 1, and finally 0.
- When the value of n is 0 then the loop ended. And, the final output is 6231
Code 👩💻
def reverse(n):
rev = 0
while(n>0):
r = n % 10
rev = (rev * 10) + r
n = n // 10
return rev
num = int(input("Enter a number: "))
print(reverse(num))
STEPS 👇
Let n = 1326
#1
r = 1326 % 10 #ans: 6
rev = (0*10) + 6 #ans: 6
n = 1326 // 10 #ans: 132
#2
r = 132 % 10 #ans: 2
rev = (6*10) + 2 #ans: 62
n = 132 // 10 #ans: 13
#3
r = 13 % 10 #ans: 3
rev = (62*10) + 3 #ans: 623
n = 13 // 10 #ans: 1
#4
r = 1 % 10 #ans: 1
rev = (623*10) + 1 #ans: 6231
n = 13 // 10 #ans: 0