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.

  1. Take user input

    • The user enters a multi-digit number, which is stored in num.
  2. Initialize a variable rev to store the reversed number

    • rev = 0 is used to build the reversed number step by step.
  3. Extract each digit using a while loop

    • digit = num % 10 gets the last digit of num.
    • rev = rev * 10 + digit shifts existing digits in rev left and adds the new digit.
    • num = num // 10 removes the last digit from num to process the next one.
  4. Repeat until all digits are processed

    • The loop runs until num becomes zero.
  5. Print the reversed number

    • After the loop ends, rev holds the reversed number, which is printed.

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