Accepted - Check for overflow before it happens


  • 0
    C

    I was asked to find a solution to this problem and was very confused by all the responses I saw on the web. It appears that most solutions "check for overflow after it occurs" which is supposedly non-compliant. From what I was reading you must check for an overflow before it occurs.

    In this problem, an overflow can occur here during both the "multiplication" and the "addition" phases of finding a reversed number. So my code checks at both those points. If an overflow is detected at either point, it returns 0, otherwise it continues.

    No consideration was given to "optimization" for speed, since it reduces readability, but I'm sure you can find many ways to optimize this solution.

    class Solution {
        public int reverse(int x) {
            int r = 0;
            while (x!=0){
                
                // Check for overflow on multiplication. Continue only-if no overflow detected.
                if ((r>0 && r > Integer.MAX_VALUE/10) || (r<0 && r < Integer.MIN_VALUE/10)) return 0;
                
                r *= 10;
                int lastDigit = x%10;
                
                // Check for overflow on addition. Continue only-if no overflow detected.
                if ((r>0 && r > Integer.MAX_VALUE-lastDigit) || (r<0 && r < Integer.MIN_VALUE-lastDigit)) return 0;
                
                r += lastDigit;
                x /= 10 ;
            }
    	return r;  
        }
    }
    

  • 0
    C

    A cleaner faster solution for Java Users:

    class Solution {
        public int reverse(int x) {
            int r = 0;
            while (x!=0){
                try {r = Math.addExact(Math.multiplyExact(r,10),x%10);}
                catch (ArithmeticException e){return 0;}
                x/=10;
            }
            return r;  
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.