Reverse Integer — Day 46(Python)

Annamariya Tharayil
2 min readDec 15, 2020
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.

Note:
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:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

Constraints:

  • -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.

class ReverseInt:
def reverse(self, x: int) -> int:
negative = False
output = 0
if x < 0:
negative = True
x *= -1
while x:
output = output*10 + x%10
x = x//10
if((negative == False and output > pow(2, 31)-1 )or(negative and output > pow(2, 31))) :
return 0
if negative:
output *= -1

return output

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.

--

--