InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Reverse Integer

medium Original ↗ 00:00

Problem

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

The environment can only store a signed 32-bit integer, meaning 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 = 123321 Digits 1 2 3 reversed are 3 2 1.
  • x = -123-321 Reverse the magnitude 123321, reattach the sign.
  • x = 12021 Reversed digits are 0 2 1; leading zeros drop, leaving 21.
  • x = 15342364690 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 return `0` the moment it fails, so you never form the out-of-range value.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug