Java overflow avoidance discussion


  • 0

    The tricky part of this problem is essentially the overflow handling.
    Here is how I handle it. In practice, the rev == Integer.MAX_VALUE / 10 && x % 10 > Integer.MAX_VALUE % 10 case will not necessary if you observe the actually digits of Integer.MAX_VALUE. But how do you know if you cannot remember that max number? Also if we are given a long instead of int, things might be different. So I add rev == Integer.MAX_VALUE / 10 && x % 10 > Integer.MAX_VALUE % 10 to guarantee it is safe.
    Is there any better way?

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

Log in to reply
 

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