Reverse Integer — Day 46(Python)

Image for post
Image for post
Photo by Sam Barber on Unsplash

Today we will be solving another “Easy” tagged question from Leetcode.

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For this problem, assume that your function returns 0 when the reversed integer overflows.

Example 1:

Example 2:

Example 3:

Example 4:


  • -2^31 <= x <= 2^31 - 1

We need to keep in mind that the given system can handle only 32-bit signed integers, Hence we should be careful while reversing the integer.

As the first step, we need to check if the given number is positive or negative. An appropriate flag needs to be set based on the sign of the given integer.

Next, we need to run the loop until we have digits in our number.

To reverse the integer, we need to get the last digits and put them in the front. To get the last digits, we would take the modulus of the given number by 10. The obtained number is then multiplied by 10. The previous number is divided by 10 so that we can omit the last digit as we have already processed it.

Each time the number is multiplied by 10, we need to ensure that the number is well within the constraint given. Based on the sign flag, we can convert the obtained answer to a negative number if required.

Complexity analysis.

Time Complexity

We will be running the loop until we traverse through all the digits in the given number, hence the time complexity is the number of digits.

Space Complexity.

We are not making use of any data structure to store intermediate results. Therefore space complexity is O(1).

I would love to hear your feedback about my posts. Do let me know if you have any comments or feedback.

Software Engineer. Find me @

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store