Python Program To Reverse a Number

Problem Definition

Create a Python program to reverse a number in Python.


This article will show multiple solutions for reversing a number in Python.

Reversing a number mathematically

The algorithm below is used to reverse a number mathematically with time complexity of O(log n) where n is input number.


Input : num

(1) Initialize rev_num = 0

(2) Loop while num > 0

  • (a) Multiply rev_num by 10 and add remainder of num divide by 10 to rev_num
  • (b) Divide num by 10

(3) Return rev_num


num = 12345

rev_num = 0

while num != 0:
    rev_num = rev_num * 10
    rev_num = rev_num + (num%10)
    num = num // 10



Using reversed() method

Python’s built in reversed() method returns an iterator that accesses the given sequence in the reverse order.


# input
num = 1234

rev_iterator = reversed(str(num))
rev_num = "".join(rev_iterator)




Note that the reversed() method doesn’t accept integer as a parameter therefore data type is converted to a string.

Sincereversed() returns an iterator we need to join it before printing it out.

Using slicing

Python string supports slicing to create substring.


The slicing starts with the start_pos index (included) and ends at the end_pos index (excluded). The step parameter is used to specify the steps to take from the start to end index.


num = 123

rev_num = str(num)[::-1]




Since slicing work on a string we need to convert the number to a string, then create a slice that starts with the length of the string, and ends at index 0 with a step of -1.

Suggested read:

Support Django Central

If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me.
Buy Me a Coffee at

Leave a Comment