Python - Reverse the Digits of a Number
Problem Statement
Brief Description
According to the problem statement we have to write a program in Python that will take an integer value as input from the user through the keyboard and will to reverse the digits present in that number.
For example, if the user enters 157 as input, the program will generate 751 as output.
Program
num=int(input("Enter a number: "))
rev=0
temp=num
while temp!=0:
rem=temp%10
rev=rev*10+rem
temp=temp//10 #OR temp//=10
print("Reverse of",num,"is",rev)
Output
Explanation
- 4 variables namely num, temp, rev and rem are used.
- Initially 0 is stored in rev.
- The integer value entered by the user is stored in num.
- A copy of the entered value is stored in temp.
num | temp!=0 | rem=temp%10; | rem | rev=rev*10+rem; | rev | temp=temp/10; | temp | Comment |
---|---|---|---|---|---|---|---|---|
157 | - | - | - | - | 0 | - | 157 | Initial Values |
157 | 157!=0 ↓ True | rem=157%10; | 7 | rev=0*10+7; | 7 | temp=157/10; | 15 | Iteration 1 |
157 | 15!=0 ↓ True | rem=15%10; | 5 | rev=7*10+5; | 75 | temp=15/10; | 1 | Iteration 2 |
157 | 1!=0 ↓ True | rem=1%10; | 1 | rev=75*10+1; | 751 | temp=1/10; | 0 | Iteration 3 |
157 | 0!=0 ↓ False | - | - | - | - | - | - | While loop stops working as temp!=0 is evaluated to False |
- At first value of temp is checked to see whether it is 0 or not.
- The condition temp!=0 will produce either True or False after evaluation.
- If it is True, the statements written within while loop are executed and the loop continues to iterate till the condition is True.
- If it is False then the statements written within while loop are not executed and the control goes to the statement written immediately after the loop.
Within while loop, at first the last digit is extracted from the value stored in temp by performing modulo division operation using the expression temp%10. Thus the expression temp%10Â will give the remainder after integer division which is the last digit of the value stored in temp and the result is stored in rem.Â
After that the value stored in rev is multiplied with 10 and the value obtained in rem is added with it and the result is stored in the same variable i.e. rev. The expression rev=rev*10+rem; is used to construct a number from individual digits.
The value stored in temp is divided by 10 to remove the last digit of the value stored in it and the result is stored in the same variable i.e. temp.
Thus the above process is used to reverse the digits present in the given number.
The final result is stored in rev.Â
Finally the result along with the value entered by the user is displayed on the output screen.