Sweaty Imposter

Reverse Integer

MediumMath & GeometryNeetCode 150MidOpen on LeetCodeUpdated

You're given a signed 32-bit integer x. Return x with its digits reversed, keeping its sign. If the reversed value falls outside the signed 32-bit range [-2^31, 2^31 - 1], return 0. Assume you can't store 64-bit integers, so the overflow has to be caught before it happens.

Examples

x = 4071 returns 1704

The digits 4, 0, 7, 1 read back to front are 1, 7, 0, 4.

x = -560 returns -65

The trailing zero becomes a leading zero and drops away, and the sign stays.

x = 2000000009 returns 0

The reversed value 9000000002 is larger than 2^31 - 1 = 2147483647, so the answer is 0.

Constraints

  • -2^31 <= x <= 2^31 - 1

Hints

Hint 1

x % 10 gives the last digit and x / 10 drops it. How do you append a digit to the end of the result?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

Pop digits off the end of x with x % 10 and x / 10, and push each onto the result with result * 10 + digit. Check before every push: with MAX = 2^31 - 1, the push overflows when result > MAX / 10, or when result == MAX / 10 and the digit is above 7. The negative side mirrors this against MIN / 10 and -8. In Java, % and / truncate toward zero, so a negative x yields negative digits and one loop handles both signs. Python floors negative division, so the Python version reverses the absolute value and checks it against 2^31 - 1 or 2^31. O(log |x|) time, one step per digit, and O(1) space.

Time

O(log x)

Space

O(1)

Pitfall

Checking for overflow after result * 10 + digit has already run. In a 32-bit int the value has wrapped by then and can look valid. Compare against the limit divided by 10 before multiplying.

Solutions

class Solution {
    public int reverse(int x) {
        int result = 0;
        while (x != 0) {
            int digit = x % 10;
            x /= 10;
            if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && digit > 7)) return 0;
            if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && digit < -8)) return 0;
            result = result * 10 + digit;
        }
        return result;
    }
}
Drill This