Skip to content
On this page

Reverse Integer Medium

Question

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).

txt
Input: x = 123
Output: 321
txt
Input: x = -123
Output: -321
txt
Input: x = 120
Output: 21
txt
-2^31 <= x <= 2^31 - 1

Solution

python
def reverse(x):
    if x < 0:
        sign = -1
    else:
        sign = 1
    
    x = abs(x)
    reversed_num = 0
    
    while x != 0:
        pop = x % 10
        x //= 10
        
        # Check for integer overflow
        if reversed_num > (2**31 - 1 - pop) // 10:
            return 0
        
        reversed_num = reversed_num * 10 + pop
    
    return sign * reversed_num
java
public int reverse(int x) {
    int sign = (x < 0) ? -1 : 1;
    x = Math.abs(x);
    long reversedNum = 0;
    
    while (x != 0) {
        int pop = x % 10;
        x /= 10;
        
        // Check for integer overflow
        if (reversedNum > (Integer.MAX_VALUE - pop) / 10) {
            return 0;
        }
        
        reversedNum = reversedNum * 10 + pop;
    }
    
    return (int) (sign * reversedNum);
}
javascript
function reverse(x) {
    const sign = (x < 0) ? -1 : 1;
    x = Math.abs(x);
    let reversedNum = 0;
    
    while (x !== 0) {
        const pop = x % 10;
        x = Math.floor(x / 10);
        
        // Check for integer overflow
        if (reversedNum > (Math.pow(2, 31) - 1 - pop) / 10) {
            return 0;
        }
        
        reversedNum = reversedNum * 10 + pop;
    }
    
    return sign * reversedNum;
}

Notes

You are given a signed 32-bit integer x. You need to reverse the digits of x. If the reversed value goes outside the range of a signed 32-bit integer, you should return 0.

Time and Space Complexity Analysis

The time complexity of the given solutions is O(log(x)), where x is the given integer. The number of digits in x determines the number of iterations required to reverse the digits.

The space complexity for all solutions is O(1), as they only use a few extra variables to store intermediate results.

These solutions handle the integer reversal while avoiding integer overflow by using additional checks and calculations, ensuring the final result fits within the 32-bit signed integer range.