Use Only <int> and Detect Overflow Beforehand


  • 1
    M

    I see many answers directly use <long> to avoid overflow.

    But since we only need to figure out the following inequality:
    rev * 10 + org % 10 > Integer.MAX_VALUE

    So we can simply move the inequality into:
    rev > (Integer.MAX_VALUE - org % 10) / 10
    which will never overflow, and use this new inequality to detect overflow beforehand.

        /** Early overflow detection. */
        static int reverseInt(int org) {
            int rev = 0;
            while (org != 0) {
                int digit = org % 10;
                if (rev > 0 && (Integer.MAX_VALUE - digit) / 10 < rev ) return 0;
                if (rev < 0 && (Integer.MIN_VALUE - digit) / 10 > rev ) return 0;
                else rev = rev * 10 + digit;
                org /= 10;
            }
            return rev;
        }
    
        /** Use long to avoid overflow */
        static int reverseInt(int org) {
            long rev = 0;
            while (org != 0) {
                rev = rev * 10 + org % 10;
                if (rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE) return 0;
                org /= 10;
            }
            return (int) rev;
        }
    

Log in to reply
 

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