LeetCode-7 Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

The trick in this solution is to avoid overflow.
To do so, note that if overflow happens, the reversed result cannot be reconstructed to the original value.

This one is related the 190 Reverse Bits problem, the basic idea is the same, but as we do this one with integer, the base is 10 rather than 1 bit.

class Solution {
    public int reverse(int x) {      
        int res = 0;
        while(x!=0){
            int tail = x%10;
            int newres = res*10+tail;
            // this is to check if the reversed result can reconstruct the original value
            if((newres-tail)/10!=res) return 0;
            res =newres;
            x/=10;
        }
        return res;

    }
}