Link: 7. Reverse Integer - Medium
Track: Amazon Tag

Question

Restate the problem

  • Given a signed integer x
  • Return its digits reversed
    • if range outside the [-2**31, 2**31 - 1], return 0

While reversing, check for overflow at each step


Method 1 - Optimal
Method 2

Method 1

Approach

  1. Repeatedly take the last digit with num = x % 10
  2. Remove the last digit with x //= 10
  3. Append the digit to the result with res = res * 10 + num

Complexity

  • Time Complexity: O(d)
    • d is the number of digit x
  • Space Complexity: O(d)

Edge Case

Code

class Solution:
    def reverse(self, x: int) -> int:
        MAX = 2**31 - 1
        MIN = -2**31
        
        res = 0
        sign = 1 if x > 0 else -1
        x = abs(x)
        while x:
            num = x % 10
            x = x // 10
 
            res = res * 10 + num
            if res < MIN or res > MAX:
                return 0
        
        return sign * res

Method 2

Code

class Solution:
    def reverse(self, x: int) -> int:
        MAX = 2**31 - 1
        MIN = -2**31
        
        sign = 1
        if x < 0:
            sign = -1
            x *= -1
        
        res = int(str(abs(x))[::-1]) * sign
        if res < MIN or res > MAX:
            return 0
 
        return res

History

  • Jan-22-2026 Peeked
    • Integers don’t have a .reverse() method (only lists do).
    • Math way to reverse an integer