Post

LC 7 - Reverse Integer

LC 7 - Reverse Integer

Question

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

1
2
Input: x = 123
Output: 321

Example 2:

1
2
Input: x = -123
Output: -321

Example 3:

1
2
Input: x = 120
Output: 21

Constraints:

  • -231 <= x <= 231 - 1

Question here and solution here

Solution

concept

Nil

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def reverse(self, x: int) -> int:
        MIN = -2147483648 # -2^31
        MAX = 2147483647 # 2^31 - 1
        
        ans = 0
        while x:
            # in python for -ve num, e.g. -1%10 = 9, so we use a math lib
            digit = int(math.fmod(x,10))
            # in python for -ve num, e.g. -1//10 = -1. so we do it this way for int div
            x = int(x/10)
            # we cannot access num > 2147483647 directly due to 32 bit restriction
            # so we compare 214748364 first, if our reversed value is larger than this, then for sure curr_num*10 will be larger
            if (ans > MAX//10 or
               (ans == MAX//10 and digit >= MAX%10)):
               return 0 
            if (ans < MIN//10 or
               (ans == MIN//10 and digit <= MIN%10)):
               return 0
            ans = (ans*10)+digit
        return ans

Complexity

time: $O(1)$
space: $O(1)$

This post is licensed under CC BY 4.0 by the author.