Reverse Integer medium

Problem Statement

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Example 1

Input: x = 123 Output: 321

Example 2

Input: x = -123 Output: -321

Example 3

Input: x = 120 Output: 21

Steps

  1. Handle the sign: Determine the sign of the input integer x. Store the sign (1 or -1) separately. Make x positive for easier processing.
  2. Reverse the digits: Use a while loop to iterate through the digits of x. In each iteration, extract the last digit using the modulo operator (% 10), add it to the reversed integer, and remove the last digit from x using integer division (/ 10).
  3. Check for overflow: After reversing, check if the reversed integer falls within the 32-bit signed integer range. If it's outside the range, return 0. Otherwise, apply the original sign and return the reversed integer.

Explanation

The core idea is to repeatedly extract the last digit, build the reversed number, and handle potential overflow. The modulo operator (%) gives the remainder after division, effectively extracting the last digit. Integer division (/) discards the last digit. We multiply the reversed number by 10 to shift existing digits to the left, making space for the new last digit. The overflow check prevents unexpected behavior or errors.

Code

function reverse(x: number): number {
    let sign = x >= 0 ? 1 : -1;
    x = Math.abs(x);
    let reversed = 0;

    while (x > 0) {
        let pop = x % 10;
        x = Math.floor(x / 10);

        // Check for overflow before updating reversed
        if (reversed > Math.floor(Number.MAX_SAFE_INTEGER / 10) || (reversed === Math.floor(Number.MAX_SAFE_INTEGER / 10) && pop > 7)) {
            return 0;
        }
        if (reversed < Math.floor(Number.MIN_SAFE_INTEGER / 10) || (reversed === Math.floor(Number.MIN_SAFE_INTEGER / 10) && pop < -8)) {
            return 0;
        }

        reversed = reversed * 10 + pop;
    }

    return reversed * sign;
}

Complexity

  • Time Complexity: O(log10(n)), where n is the input integer. The number of iterations is proportional to the number of digits in the integer.
  • Space Complexity: O(1). The algorithm uses a constant amount of extra space.