Algorithm

Reverse Integer Algorithm

Reverse the digits of an integer. Keep the sign. Return 0 if the result overflows a 32-bit signed integer.

10 Mar 2024

Reverse Integer Algorithm

Reverse the digits of an integer. Keep the sign. Return 0 if the result overflows a 32-bit signed integer.

123 becomes 321. -456 becomes -654. Simple enough — until overflow bites you.

The intuition

Peel digits off the end with modulo, build the reversed number by multiplying by 10 and adding. It's like reading a number backwards, digit by digit.

The hidden trap: 32-bit integer overflow. In JavaScript there's no native 32-bit int, but the problem constrains you to the range [-2^31, 2^31 - 1]. Check before you multiply.

Javascript
const reverseInteger = (number) => {
    const MAX = Math.pow(2, 31) - 1;
    const MIN = -Math.pow(2, 31);
    let result = 0;

    while (number !== 0) {
        const digit = number % 10;
        number = Math.trunc(number / 10);

        if (result > MAX / 10 || result < MIN / 10) {
            return 0;
        }

        result = result * 10 + digit;
    }

    return result;
};

Complexity

  • Time: O(log n) — proportional to the number of digits.
  • Space: O(1).

The real lesson

The algorithm itself is trivial. The interview question is really about edge cases: negative numbers, trailing zeros (1200 → 21), and overflow. Most people get the reversal right and miss the overflow check. That's where bugs live in production too — not in the happy path, but in the boundaries.