Python program to calculate the reverse of an integer number without using strings

In this post, I’ll show a Python program to calculate the reverse of an integer number without using strings.

One reason for not using strings is that we want to focus on the algorithm instead of getting a solution we don’t fully understand. The other one is that converting big numbers to strings is a slow process.

First, we are going to use the fact that with the log10 of a number, we can calculate the number of digits of the specific number. Yes, as I said before, knowing mathematics helps to create better programs.

So, if d is the number of digits of an integer number, then d = int (log10 n) + 1.

The next step of the algorithm will be to extract the digits of the number from right to left. Again, we won’t use strings, instead, we will use the code I wrote for you and published here.

Python code to reverse a number

Let’s see now see the python code to calculate the reverse of an integer number without using strings.

import math

def reverse(number):
    res = 0
    digits = int(math.log10(number))
    while number > 0:
        result = number % 10
        number = int(number / 10)
        res = res + (result * (10**digits))
        digits = digits - 1
    return res

In this code, we use the fact that the remainder of the division by 10, gives us the last digit. If we divide again by 10, the remainder gives us the second last digit, and so on.

Example:

  • 123 % 10 = 3
  • 12 % 10 = 2

For a longer explanation, you can check this post.

Now, let’s test the function above with the following python console application.

if __name__=='__main__':
    print (reverse(1234789))

If you execute the code, you will get the following result.

Example of output of a python program to calculate the reverse of an integer number without using strings
Example of output of a python program to calculate the reverse of an integer number without using strings

H@ppy coding!

Related posts: