Python 02: Reversing an integer in Python

Python 02: Reversing an integer in Python

Let's learn reversing given integer using Python programming. The logic explanation.

  1. Read the user input to a user variable (say num).
  2. Declare a variable (say reversed_num) and initialize '0' to it.
  3. Calculate it's percentile (%) of given number, which returns last digit of the given number.
  4. Add returned value in the above step to 10 multiple of reversed_num.
  5. Now divide given number with 10 and store the result in user variable.
  6. Repeat from step 2, till user variable value is > 0.
def reverse_integer(n):
    reversed_num = 0 # assigning zero to a variable
    while(n>0):
        remainder = n%10 # the remainder will be stored
        reversed_num = reversed_num * 10 + remainder
        n = n//10 # last digit will be removed
    return reversed_num

if __name__ == "__main__":
    num = int(input("Enter your +ve number: ")) # reading input from user
    reversed_number = reverse_integer(num)
    print(reversed_number) # prints the reversed number

Thank you for reading. Keep learning.