Python Program to reverse an integer number
Program
num = int(input("Enter multi-digit number: "))
rev = 0
while(num > 0):
digit = num % 10
rev = rev * 10 + digit
num = num // 10
print("Reversed number is:\t", rev)
This program takes a multi-digit integer as input and reverses its digits using a loop.
-
Take user input
- The user enters a multi-digit number, which is stored in
num
.
- The user enters a multi-digit number, which is stored in
-
Initialize a variable
rev
to store the reversed numberrev = 0
is used to build the reversed number step by step.
-
Extract each digit using a while loop
digit = num % 10
gets the last digit ofnum
.rev = rev * 10 + digit
shifts existing digits inrev
left and adds the new digit.num = num // 10
removes the last digit fromnum
to process the next one.
-
Repeat until all digits are processed
- The loop runs until
num
becomes zero.
- The loop runs until
-
Print the reversed number
- After the loop ends,
rev
holds the reversed number, which is printed.
- After the loop ends,
Key Takeaways
- The program extracts and reverses digits using integer division and modulus.
- It efficiently builds the reversed number without converting it to a string.
- The approach works for positive integers. If negative numbers need to be handled, modifications are required.
Output
Enter multi-digit number: 129809
Reversed number is: 908921