1

This is code from Leetcode solution. So I don't understand the if condition, why Integer.MAX_VALUE has to be divided by 10 (Interger.MAX_VALUE / 10) ?

Thank You!

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


2
  • Prevents overflow. Commented Jun 5, 2019 at 21:53
  • What’s the question for which this code was written? Commented Jun 5, 2019 at 22:03

2 Answers 2

4

The reverse(int x) function reverses the decimal digits of x. For example, if x = 102, it returns 201, and if x = -102, it returns -201.

When the reverse of x is computed, it is stored in rev. For example, for x = 102, rev takes the successive values 2, 20, 201.

At each iteration, rev is multiplied by 10, and one digit is added to it. Of course, rev cannot be greater than Integer.MAX_VALUE (2147483647). So, before multiplying rev by 10, we check whether multiplying it by 10 and adding pop would make it greater than Integer.MAX_VALUE.

We first check whether rev is greater than Integer.MAX_VALUE / 10 (214748364). If it is greater, the reverse integer does not exist. If not, then rev is less than or equal to Integer.MAX_VALUE / 10. If it is less than Integer.MAX_VALUE / 10, then even if we multiply it by 10, we can add any digit (pop) to it, and we will not exceed Integer.MAX_VALUE. However, if it is equal to Integer.MAX_VALUE / 10, then we must that make sure that pop is not > 7 (2147483647 - 214748364 * 10) because we would otherwise exceed Integer.MAX_VALUE.

The same reasoning applies to Integer.MIN_VALUE (2147483648).

Sign up to request clarification or add additional context in comments.

2 Comments

@pkim Did that answer your question?
It sure did! Thank you.
0

It's pretty straight forward. Its mainly added so that you don't hit integer memory out of bound exception.

Line 1:   rev == Integer.MAX_VALUE / 10
Line 2:  rev = rev * 10 + pop;

Let's assume the above case is true for some value. Line 1 means that 10*rev = Integer.MAX_VALUE. Line 2: rev is an integer. if as per line 1, we have encountered a case where rev = Integer.MAX_VALUE, if we add a pop on top of it, we would encounter integer memory out of bound exception. To avoid that, Line 1 is added. Sample test case to make sure Line 1 is executed is "Pass Integer.MAX_VALUE" as an input to reverse() function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.