Easy understanding and without using long or abs()


  • 0
    W

    Because there is only one case that the reversed integer will overflow, so I just test the case: (I will show how to solve overflow when the integer is positive, the other case is roughtly the same.)
    let's represent an integer as a0a1a2...an and the reversed integer as an...a2a1a0. If the integer overflows we can find that an...a2a1 * 10 + a0 > Integer.MAX_VALUE, which can be represented as an...a2a1 >(Integer.MAX_VALUE - a0) / 10 (1), while an...a2a1 will always not overflow. so when I reversed my integer with the first (n - 1) bit, I stop and inspect wether (1) is violated.
    one side note:
    we don't need to extract the sign, the result of "a % b" and "a / 10" keeps the a's sign..

    public class Solution {
        public int reverse(int x) {
            int a = x;
            int result = 0;
            // leave the last bit untreated until I'm sure that it will
            // not overflow 
            while(a / 10 != 0) {
                result = a % 10 + result * 10;
                a = a / 10;
            }
            if(x >= 0 && result > (Integer.MAX_VALUE - a % 10) / 10)
                return 0;
            if(x < 0 && result < (Integer.MIN_VALUE - a % 10) / 10)
                return 0;
            result = a % 10 + result * 10;
            return result;
        }
    
    }

Log in to reply
 

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