Python Examples

Python Program - Reverse digits of a given Integer



In Python, the reverse of a given integer can be found out by using below mentioned methods.

Method 1: Using iteration

The method involves the following steps:

Input: MyNum
Step 1: Initialize the RevNum = 0
Step 2: Iterate over MyNum while it is greater than zero.
   Step 2a: Calculate remainder of MuNum / 10
   Step 2b: Update RevNum by RevNum * 10 + remainder
   Step 2c: Update MyNum by MyNum // 10
Step 3: Return RevNum

Example:

Input: 564

RevNum: 0
Iteration 1: 
    Remainder: 564 % 10 = 4
    RevNum: 0 * 10 + 4 = 4
    MyNum: 564 // 10 = 56

Iteration 2: 
    Remainder: 56 % 10 = 6
    RevNum: 4 * 10 + 6 = 46
    MyNum: 56 // 10 = 5

Iteration 3: 
    Remainder: 5 % 10 = 5
    RevNum: 46 * 10 + 5 = 465
    MyNum: 5 // 10 = 0

return RevNum = 465

The below block of code shows the implementation of above concept:

def reverse(MyNum):
  RevNum = 0
  while MyNum > 0:
    remainder = MyNum % 10
    MyNum = MyNum // 10
    RevNum = RevNum * 10 + remainder
  return RevNum

x = 1285
y = 4567
print("Reverse of", x, "is:", reverse(x))
print("Reverse of", y, "is:", reverse(y))

The above code will give the following output:

Reverse of 1285 is: 5821
Reverse of 4567 is: 7654

Method 2: Using Recursion

The above result can also be achieved using recursive function. Consider the example below:

RevNum = 0
base = 1

def reverse(MyNum):

  global RevNum
  global base
  
  if MyNum > 0:
    reverse(MyNum//10)
    RevNum += MyNum % 10 * base
    base *= 10
  return RevNum

x = 7902
print("Reverse of", x, "is:", reverse(x))

The above code will give the following output:

Reverse of 7902 is: 2097