HomeLeetcode7. Reverse Integer - Leetcode Solutions

7. Reverse Integer – Leetcode Solutions

Description:

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.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Examples:

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Solution in Python:

To solve the problem of reversing the digits of a signed 32-bit integer in Python while ensuring that the reversed integer stays within the 32-bit range, you can follow these steps:

  1. Check the sign of the input integer: If it’s negative, work with its absolute value and remember to reapply the sign at the end.
  2. Reverse the digits: Convert the integer to a string, reverse the string, and convert it back to an integer.
  3. Check for overflow: Ensure the reversed integer falls within the 32-bit signed integer range.
  4. Return the result: Return the reversed integer if it’s within the valid range, otherwise return 0.
Python
class Solution:
    def reverse(self, x: int) -> int:
        # Define the 32-bit integer range limits
        INT_MIN, INT_MAX = -2**31, 2**31 - 1
        
        # Determine if the number is negative
        negative = x < 0
        
        # Work with the absolute value of x
        x = abs(x)
        
        # Reverse the digits by converting to string, reversing, and converting back to integer
        reversed_x = int(str(x)[::-1])
        
        # Reapply the negative sign if the original number was negative
        if negative:
            reversed_x = -reversed_x
        
        # Check if the reversed number is within the 32-bit signed integer range
        if reversed_x < INT_MIN or reversed_x > INT_MAX:
            return 0
        
        return reversed_x

# Example usage:
sol = Solution()
print(sol.reverse(123))    # Output: 321
print(sol.reverse(-123))   # Output: -321
print(sol.reverse(120))    # Output: 21
print(sol.reverse(0))      # Output: 0
print(sol.reverse(1534236469))  # Output: 0 (since it overflows 32-bit range when reversed)

Explanation of the Code:

  1. Define 32-bit Integer Limits:
    • INT_MIN is set to -231 (-2147483648).
    • INT_MAX is set to 231 – 1 (2147483647).
  2. Check for Negative Sign:
    • Use a boolean negative to check if x is negative. This will be used to reapply the negative sign after reversing the digits.
  3. Reverse the Digits:
    • Convert x to a string, reverse the string using slicing ([::-1]), and convert the result back to an integer.
  4. Reapply the Sign:
    • If the original integer was negative, reapply the negative sign to the reversed integer.
  5. Check for 32-bit Overflow:
    • If the reversed integer is outside the 32-bit signed integer range, return 0.
  6. Return the Result:
    • If the reversed integer is within the valid range, return it.

Solution in Javascript:

JavaScript
/**
 * @param {number} x
 * @return {number}
 */
var reverse = function(x) {
    // Define the 32-bit integer range limits
    const INT_MIN = -Math.pow(2, 31);
    const INT_MAX = Math.pow(2, 31) - 1;
    
    // Determine if the number is negative
    const isNegative = x < 0;
    
    // Work with the absolute value of x
    x = Math.abs(x);
    
    // Reverse the digits by converting to string, reversing, and converting back to integer
    let reversed = 0;
    while (x !== 0) {
        const pop = x % 10;
        x = Math.floor(x / 10);
        
        // Check for overflow before actually reversing
        if (reversed > Math.floor(INT_MAX / 10) || 
           (reversed === Math.floor(INT_MAX / 10) && pop > 7)) {
            return 0;
        }
        
        if (reversed < Math.ceil(INT_MIN / 10) || 
           (reversed === Math.ceil(INT_MIN / 10) && pop < -8)) {
            return 0;
        }
        
        reversed = reversed * 10 + pop;
    }
    
    // Reapply the negative sign if the original number was negative
    if (isNegative) {
        reversed = -reversed;
    }
    
    // Check if the reversed number is within the 32-bit signed integer range
    if (reversed < INT_MIN || reversed > INT_MAX) {
        return 0;
    }
    
    return reversed;
};

// Example usage:
console.log(reverse(123));    // Output: 321
console.log(reverse(-123));   // Output: -321
console.log(reverse(120));    // Output: 21
console.log(reverse(0));      // Output: 0
console.log(reverse(1534236469));  // Output: 0 (since it overflows 32-bit range when reversed)

Solution in Java:

Java
class Solution {
    public int reverse(int x) {
        // Define the 32-bit integer range limits
        final int INT_MIN = -2147483648; // Integer.MIN_VALUE
        final int INT_MAX = 2147483647;  // Integer.MAX_VALUE
        
        int reversed = 0;
        
        // Process each digit of the input number
        while (x != 0) {
            int pop = x % 10;  // Extract the last digit
            x /= 10;  // Remove the last digit
            
            // Check for overflow before actually reversing
            if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && pop > 7)) {
                return 0; // Will overflow
            }
            if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && pop < -8)) {
                return 0; // Will underflow
            }
            
            reversed = reversed * 10 + pop; // Append the digit to the reversed number
        }
        
        return reversed; // Return the reversed number
    }
    
    // Main method for testing
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.reverse(123));    // Output: 321
        System.out.println(sol.reverse(-123));   // Output: -321
        System.out.println(sol.reverse(120));    // Output: 21
        System.out.println(sol.reverse(0));      // Output: 0
        System.out.println(sol.reverse(1534236469));  // Output: 0 (since it overflows 32-bit range when reversed)
    }
}

Solution in C#:

C#
public class Solution {
    public int Reverse(int x) {
        // Define the 32-bit integer range limits
        const int INT_MIN = int.MinValue; // -2147483648
        const int INT_MAX = int.MaxValue; // 2147483647
        
        int reversed = 0;
        
        // Process each digit of the input number
        while (x != 0) {
            int pop = x % 10;  // Extract the last digit
            x /= 10;  // Remove the last digit
            
            // Check for overflow before actually reversing
            if (reversed > INT_MAX / 10 || (reversed == INT_MAX / 10 && pop > 7)) {
                return 0; // Will overflow
            }
            if (reversed < INT_MIN / 10 || (reversed == INT_MIN / 10 && pop < -8)) {
                return 0; // Will underflow
            }
            
            reversed = reversed * 10 + pop; // Append the digit to the reversed number
        }
        
        return reversed; // Return the reversed number
    }

    
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular