Magicsheet logo

Reverse Integer

Medium
75%
Updated 6/1/2025

Reverse Integer

What is this problem about?

The Reverse Integer interview question asks you to reverse the digits of a signed 32-bit integer. If the reversed integer overflows the 32-bit signed integer range [-2^31, 2^31 - 1], return 0. For example, reversing 123 gives 321, reversing -123 gives -321, and reversing 120 gives 21 (leading zeros are dropped).

Why is this asked in interviews?

This problem is asked at Apple, Samsung, Uber, Goldman Sachs, Microsoft, Meta, Amazon, LinkedIn, Google, Bloomberg, and Adobe because it tests awareness of integer overflow — a critical concern in systems programming, embedded devices, and financial calculations. Simply reversing the digits in Python (which has arbitrary-precision integers) is easy; the challenge is correctly handling overflow bounds without using 64-bit integers.

Algorithmic pattern used

The pattern is digit extraction with overflow checking. Extract digits one by one using modulo and integer division. Build the reversed number incrementally, checking for overflow before each multiplication step. The overflow condition: before doing result = result * 10 + digit, check if result > (2^31 - 1) // 10 (positive overflow) or result < (-2^31) // 10 (negative overflow). In Python, you can check after building and then compare against the 32-bit bounds.

Example explanation

Input: x = -4321

Sign: negative. Process absolute value 4321.

  • Extract digits: 1, 2, 3, 4.
  • Build reversed: 1 → 12 → 123 → 1234.
  • Apply sign: -1234.
  • Check: -1234 is within [-2^31, 2^31-1] → return -1234.

Input: x = 1534236469.

  • Reversed: 9646324351.
  • Check: 9646324351 > 2^31 - 1 (2147483647) → overflow → return 0.

Common mistakes candidates make

  • Not handling negative numbers — x % 10 in Python gives positive remainders even for negative numbers.
  • Forgetting the overflow check entirely, producing wrong results for large reversed values.
  • Using string reversal without handling leading zeros and sign separately.
  • Converting to string, reversing, and converting back without proper overflow detection.

Interview preparation tip

For the Reverse Integer coding problem, the math interview pattern with overflow handling is the key challenge. In Python, the overflow check is simple — build the number, then check bounds. In Java or C++, overflow must be checked before each multiplication step. Interviewers at Samsung and Qualcomm (hardware-focused companies) often focus on the overflow handling logic — explain it explicitly: "I check if the result would exceed INT_MAX before multiplying by 10." This demonstrates low-level awareness.

Similar Questions