Reverse Integer

Pattern: Maths basics

medium

Reverse the digits of a 32-bit integer and return 0 if the result would not fit, checking before each step instead of after.

The problem

You are given a 32-bit signed integer x. Return the number with its digits in reverse order, keeping the sign. If the reversed number does not fit in a 32-bit signed integer (from -2,147,483,648 to 2,147,483,647), return 0. For example, 123 becomes 321, -123 becomes -321, and 120 becomes 21. Assume you cannot use 64-bit integers.

The function name reverse matches LeetCode. Use the link above for the exact statement.

Think first

  • How do you build 321 from 123 using % 10 and / 10?
  • Reverse 1534236469 by hand. Does the result fit in 32 bits?
  • If an overflow has already happened, can you still detect it afterwards with only 32-bit numbers?

Hints

    Brute force, and why it fails

    Turn the number into text, reverse the text, parse it back into a 64-bit number, and check the range. That is correct and easy. The problem forbids 64-bit numbers on purpose, though, because the interesting part is spotting an overflow before it happens using only 32 bits.

    The key insight

    Build the reverse digit by digit, and before each result * 10 ask "would this leave the 32-bit range?". Comparing result with MAX / 10 and MIN / 10 answers that without ever computing the too-large value.

    Dry run

    10 
    21 
    32 
    x-123
    result0

    x = -123 and result = 0. In Java and C++ the remainder of a negative number is negative, so the sign takes care of itself.

    Step 1 of 5

    The plan

    result = 0
    while x != 0:
        digit = x mod 10              # keeps the sign of x in Java and C++
        x = x div 10                  # rounds toward 0 in Java and C++
        if result > MAX_INT div 10 or result < MIN_INT div 10:
            return 0                  # the next step would overflow
        result = result * 10 + digit
    return result
    

    The Python version follows the same steps on abs(x) with a limit of 2³¹ - 1 or 2³¹, and multiplies by the sign at the end, because Python's % and // round toward minus infinity.

    Complexity

    Time
    O(d)
    Space
    O(1)

    d is the number of digits, at most 10. Only a few 32-bit variables are used.

    Edge cases

    • 120 becomes 21: a leading zero simply disappears.
    • 0 stays 0, and single digits stay the same.
    • 1534236469 reversed is 9646324351, which is out of range, so the answer is 0.
    • 1463847412 reversed is 2147483641, which just fits.
    • 2147483647 and -2147483648 both overflow when reversed, so the answer is 0.
    I've built my logic, show the code

    Java

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

    C++

    class Solution {
    public:
        int reverse(int x) {
            int result = 0;
            while (x != 0) {
                int digit = x % 10;
                x = x / 10;
                if (result > INT_MAX / 10 || result < INT_MIN / 10) {
                    return 0;
                }
                result = result * 10 + digit;
            }
            return result;
        }
    };

    Python

    class Solution:
        def reverse(self, x: int) -> int:
            sign = -1 if x < 0 else 1
            rest = abs(x)
            limit = 2**31 - 1 if sign == 1 else 2**31
            result = 0
            while rest != 0:
                digit = rest % 10
                rest = rest // 10
                if result > (limit - digit) // 10:
                    return 0
                result = result * 10 + digit
            return sign * result

    Common mistakes

    • Checking for overflow after result * 10, when the value has already wrapped around.
    • Using a 64-bit variable, which works but ignores the problem's rule.
    • In Python, using % and // directly on a negative number. -123 % 10 is 7 there, not -3.
    • Taking the absolute value of -2147483648 in Java or C++, which overflows.

    Similar problems