7. Reverse Integer

Apparently, we can use x % 10 to get the first digit of a reversed integer and use x / 10 to keep going until we reverse all of the digits. When getting the reversed integer, we should be careful of integer overflow, which will be explained in the following self-documented code.

Version I

class Solution {
    public int reverse(int x) {
        int res = 0;
        // x != 0 can handle negative input, x > 0 cannot
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (res > Integer.MAX_VALUE / 10 || 
                (res == Integer.MAX_VALUE / 10 && pop > Integer.MAX_VALUE % 10)) {
                return 0;
            }
            if (res < Integer.MIN_VALUE / 10 || 
                (res == Integer.MIN_VALUE / 10 && pop < Integer.MIN_VALUE % 10)) {
                return 0;
            }
            res = res * 10 + pop;
        }
        return res;
    }
}

Version II

class Solution {
    public int reverse(int x) {
        int res = 0;
        // x != 0 can handle negative input, x > 0 cannot
        while (x != 0) {
            // either positive overflow or negative overflow will cause inequality
            if (res * 10 / 10 != res) {
                return 0;
            }
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
}