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
- if range outside the
While reversing, check for overflow at each step
Method 1 - Optimal
Method 2
Method 1
Approach
- Repeatedly take the last digit with
num = x % 10 - Remove the last digit with
x //= 10 - Append the digit to the result with
res = res * 10 + num
Complexity
- Time Complexity: O(d)
- d is the number of digit
x
- d is the number of digit
- 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 * resMethod 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 resHistory
- Jan-22-2026 Peeked
- Integers don’t have a
.reverse()method (only lists do). - Math way to reverse an integer
- Integers don’t have a