Solution: Reverse Integer

Let’s solve the Reverse Integer problem using the Math and Geometry pattern.

Statement

Given a 32-bit signed integer num, reverse its digits and return the result. If the reversed number exceeds the 32-bit signed integer range [231,2311][−2^{31},2^{31}−1], return 00.

Assume the environment does not support storing 64-bit integers (signed or unsigned).

Constraints:

  • 231-2^{31} \leq num 2311\leq2^{31}-1

Solution

The solution reverses the digits of num while ensuring that the result stays within the bounds of a 32-bit signed integer. If the input number is negative, it converts it to its absolute value to simplify processing. The main logic involves repeatedly extracting the last digit of nums, reducing num by removing this digit, and appending the digit to the reversed result.

Before appending each digit, the solution checks if the operation would cause the result to exceed the 32-bit signed integer limit. If an overflow is detected, the function returns 00. The solution returns the reversed result once the num is fully processed (reduced to 00). If the original number was negative, the result is negated before returning.

The detailed steps of the implementation of the solution are as follows:

  1. Initialize the below variables:

    1. Initialize INT_MAX with the maximum value of a 32-bit signed integer.

    2. Initialize result = 0 to store the reversed number.

    3. Determine if the number is negative: isNegative = num < 0.

  2. If num is negative, convert it to its absolute value: num = -num.

  3. Iterate through the digits of num while num != 0:

    1. Extract the last digit: digit = num % 10.

    2. Remove the last digit from num: num / = 10.

  4. Before updating the result, verify that appending the new digit will not cause an overflow:

    1. If result > (INT_MAX - digit) / 10, return 00 (overflow detected).

  5. Update result = result * 10 + digit to append the extracted digit to the reversed number.

  6. If the original number was negative, return -result. Otherwise, return result.

Let’s look at the following illustration to get a better understanding of the solution:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.