Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows.

Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows.
def rev(x):
    s = -1 if x < 0 else 1
    r = int(str(abs(x))[::-1]) * s
    return r if -2**31 <= r <= 2**31 - 1 else 0
print(rev(-120), rev(1534236469), rev(-2147483412))
What is printed?
  1. A. -21 0 -2143847412
  2. B. -021 0 -2143847412
  3. C. -21 9646324351 -2143847412
  4. D. 21 0 -2143847412

Correct answer: A. -21 0 -2143847412

Trailing zeros vanish (−120 → −21). 1534236469 reversed is 9646324351, above 2³¹ − 1, so 0. −2147483412 reversed is −2143847412, which still fits. In C++/Java you must check before multiplying by 10 (r > INT_MAX/10) because the overflow itself is the bug.

More Coding Interview Problems questions

Exams that ask this topic