(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
Python Program to reverse the digits of a number
The following is a Python program to reverse the digits of a number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Program to reverse the digits of a number literally
# Input = 1234
# Output = 4321
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
rem = num % 10 # extract the last digit
reverse = reverse * 10 + rem # append rem to the end of the reversed number
num //= 10 # drop the last digit
print("Reversed number: ", reverse)
|
Sample Run 1:
1 2 | Enter a number: 1478
Reversed number: 8741
|
Sample Run 2:
1 2 | Enter a number: 12799
Reversed number: 99721
|
Try it out:
To reverse the digits of a number literally, here is the algorithm:
Extract the rightmost digit of the number being reversed.
rem = num % 10
Increase the previously reversed integer by a factor of 10 (this has the effect of moving ones digit to the tens place, tens digit to the hundreds place and so on), and then add it to the recently extracted digit (this has the effect of placing the digit at the ones place) to obtain the current value of
reverse
.reverse = reverse * 10 + rem
The
reverse
variable starts off with0
and in each iteration it contains the partially reversed number. By the time the loop terminates, thereverse
will contain the completely reversed number.Drop the rightmost digit of the digit being reversed.
num = num // 10
Repeat steps 1-3, until the number being reversed is reduced to
0
.
Assuming, num = 4819
, the while
loop proceeds as follows:
Iteration | num |
rem = num % 10 |
reverse = reverse * 10 + rem |
num //= 10 |
---|---|---|---|---|
1 | num = 4819 |
4819 % 10 = 9 |
reverse = 0 * 10 + 9 = 9 |
4819 // 10 = 481 |
2 | num = 481 |
481 % 10 = 1 |
reverse = 9 * 10 + 1 = 91 |
481 // 10 = 48 |
3 | num = 48 |
48 % 10 = 8 |
reverse = 91 * 10 + 8 = 918 |
48 // 10 = 4 |
4 | num = 4 |
4 % 10 = 4 |
reverse = 918*10+4 = 9184 |
4 // 10 = 0 |
Other Tutorials (Sponsors)
This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
View Comments