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

Steps:

  1. Handle the sign: Determine the sign of the input integer x. Store the sign (1 for positive, -1 for negative) in a variable. Then, work with the absolute value of x.

  2. Reverse the digits: Convert the absolute value of x to a string, reverse the string, and convert it back to an integer. We can use string manipulation for simplicity.

  3. Check for overflow: Before returning the reversed integer, check if it falls within the 32-bit signed integer range [-231, 231 - 1]. If it's outside this range, return 0.

  4. Apply the sign: Multiply the reversed integer by the stored sign to restore the original sign.

Explanation:

The solution efficiently handles both positive and negative integers. String manipulation provides a clear and concise way to reverse the digits. The overflow check ensures that the function adheres to the problem's constraints. Direct integer manipulation without strings is also possible but can be slightly more complex to avoid potential integer overflow issues during the reversal process itself.

Code:

def reverse(x: int) -> int:
    """
    Reverses a 32-bit signed integer.  Returns 0 if reversing causes overflow.
    """
    sign = -1 if x < 0 else 1
    x = abs(x)
    reversed_x = int(str(x)[::-1])  # Efficient string reversal

    #Check for overflow
    min_int = -2**31
    max_int = 2**31 -1
    if reversed_x < min_int or reversed_x > max_int:
        return 0
    
    return reversed_x * sign


Complexity:

  • Time Complexity: O(log10(n)), where n is the absolute value of the input integer. This is because the number of digits in n is proportional to log10(n), and we iterate through these digits.
  • Space Complexity: O(log10(n)) in the worst case, due to the string representation of the integer. In practice, this is a very small constant space overhead.