InterviewPrepKit

Home / Coding / Bit Manipulation

Reverse Integer

medium Original β†—
Solving tips
  • Peel digits with rev = rev*10 + (n % 10) and n //= 10; the whole solution is one loop over the digits.
  • Check overflow BEFORE the multiply-add, never after: rev*10+digit fits iff rev <= (limit - digit)//10; bail out with 0 the moment it fails so you never form the out-of-range value.
  • Mind the asymmetric 32-bit bound: positive answers cap at 2^31-1 but negative magnitudes reach 2^31, so pick limit by sign.
  • Work on abs(x) so % and // behave as base-10 digit extraction (Python's % on negatives rounds toward -inf); O(log|x|) time, O(1) space.

Problem

Given a signed 32-bit integer x, return x with the order of its decimal digits reversed. The sign is preserved (reversing a negative number stays negative).

The catch: the environment can only store a signed 32-bit integer, i.e. values in the range [-2^31, 2^31 - 1] = [-2147483648, 2147483647]. If the reversed value falls outside that range, return 0. You must detect the overflow without relying on a wider integer type to hold the intermediate result.

Examples

  • x = 123 β†’ 321 Digits 1 2 3 reversed are 3 2 1.
  • x = -123 β†’ -321 Reverse the magnitude 123 β†’ 321, reattach the sign.
  • x = 120 β†’ 21 Reversed digits are 0 2 1; leading zeros vanish, leaving 21.
  • x = 1534236469 β†’ 0 The reverse 9646324351 exceeds 2147483647, so it overflows and the answer is 0.

Constraints

  • -2^31 <= x <= 2^31 - 1 (x fits in a signed 32-bit int).
  • The result must also fit in a signed 32-bit int, otherwise return 0.
  • No 64-bit / big-integer type is available to hold the reversed value β€” the overflow check must happen before it would occur.

Think about it first

Hint 1 You can peel digits off the right end with `% 10` and drop them with `// 10`, building the reversed number as `rev = rev * 10 + digit`. The whole problem is one loop over the digits.
Hint 2 The only hard part is the overflow. The 32-bit ceiling is `INT_MAX = 2^31 - 1 = 0x7FFFFFFF`. Before you do `rev = rev * 10 + digit`, ask whether that operation *would* cross the ceiling.
Hint 3 `rev * 10 + digit` stays in range exactly when `rev <= (limit - digit) // 10`, where `limit` is the magnitude bound (`2^31 - 1` for a positive answer, `2^31` for a negative one). Check that guard each iteration and bail out with `0` the moment it fails β€” you never form the out-of-range value at all.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.