Reverse Integer

You are given a signed 32-bit integer x. Return the integer whose decimal digits are those of x in reverse order, keeping the sign of x. Zeros that end up at the front after reversing simply disappear, so 560 becomes 65.

If the reversed value does not fit in a signed 32-bit integer, that is, it falls outside [-231, 231 - 1], return 0 instead.

Pretend your machine cannot hold 64-bit integers: detect the overflow without ever storing a value outside the 32-bit range.

Example 1

Input: x = 472 Output: 274 Why: The digits 4 7 2 read backwards give 274.

Example 2

Input: x = -905 Output: -509 Why: The sign stays in front: -905 becomes -509.

Example 3

Input: x = 560 Output: 65 Why: The trailing zero becomes a leading zero and is dropped.

Constraints

  • -231 <= x <= 231 - 1

Pattern Path · Math, Bits & Strings · problem 41 of 169

You can peel off the last digit of a number with % 10 and remove it with integer division by 10. How do you append a digit to the end of another number?
Building the result as result * 10 + digit reverses the digits. The only hard part is noticing overflow before it happens.
Before multiplying, compare result with (231 - 1) // 10 (and with the last allowed digit when equal). Working with the absolute value and restoring the sign at the end keeps the check to one side.
Target: O(log |x|) time, O(1) extra space.

Start simple

Convert to a string, reverse it and parse it back, then range-check: O(d) time, but it relies on parsing a value that may not fit in 32 bits.

The key idea

Reverse the digits arithmetically. Repeatedly take the last digit of x with x % 10, drop it with x // 10, and push it onto the result with result = result * 10 + digit. Trailing zeros of x become leading zeros of the result and vanish automatically.

The interesting part is overflow. The step result * 10 + digit exceeds LIMIT = 231 - 1 exactly when result > LIMIT // 10, or result == LIMIT // 10 and digit > LIMIT % 10. Checking that before the multiplication means no intermediate value ever leaves the 32-bit range.

To handle the sign simply, reverse the absolute value and reapply the sign at the end. The limit for negative results is one larger in magnitude (231), but the only reversal with magnitude exactly 231 would come from the input 8463847412, which is itself outside the 32-bit range. So checking against 231 - 1 is correct for both signs.

The loop runs once per digit, at most 10 times.

Complexity

  • Time: O(log |x|)
  • Space: O(1)

Python

class Solution:
    def reverse(self, x):
        LIMIT = 2**31 - 1
        sign = -1 if x < 0 else 1
        x = abs(x)
        result = 0
        while x:
            digit = x % 10
            x //= 10
            # Would result * 10 + digit exceed LIMIT? Check before computing it.
            if result > LIMIT // 10 or (result == LIMIT // 10 and digit > LIMIT % 10):
                return 0
            result = result * 10 + digit
        return sign * result

JavaScript

var reverse = function(x) {
  const LIMIT = 2 ** 31 - 1;
  const sign = x < 0 ? -1 : 1;
  x = Math.abs(x);
  let result = 0;
  while (x > 0) {
    const digit = x % 10;
    x = Math.floor(x / 10);
    // Would result * 10 + digit exceed LIMIT? Check before computing it.
    if (result > Math.floor(LIMIT / 10) || (result === Math.floor(LIMIT / 10) && digit > LIMIT % 10)) {
      return 0;
    }
    result = result * 10 + digit;
  }
  return sign * result;
};

What the interviewer is checking

The digit loop is easy; the interviewer is watching how carefully you reason about overflow and negative numbers without leaning on a bigger integer type.

Mistakes to avoid

  • Checking for overflow after multiplying, when in a 32-bit language the value has already wrapped around.
  • In Python, using % and // on negative numbers, which round toward negative infinity (-905 % 10 is 5, -905 // 10 is -91).
  • Taking abs(-231) in a 32-bit type, which overflows.
  • Forgetting that the result for an overflowing reversal is 0, not a clamped value.

Follow-ups to expect

  • How would you check whether an integer is a palindrome? (Reverse half the digits.)
  • How would you reverse the bits instead of the digits? (Shift and OR, 32 times.)
  • What about 64-bit inputs? (Same check with the 64-bit limit.)

In real software

Safe integer parsing and arithmetic in parsers, checksum code and embedded firmware all need the same check-before-you-multiply overflow guard.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url