Leetcode 7. Reverse Integer

Given a 32-bit signed integer, inverts the number in the integer.

描述 1:

输入:123出出:321

样2:

输入:-123 :-321

Example 3:

输入:120output:21

Note:

Suppose our environment can only store A 32-bit signed integer whose value range is [−231, 231 − 1]. According to this assumption, if the inverted integer overflows, it returns 0.

思维:

The hardest part of this question is the overflow problem after the reverse, so you can't use the string method to reverse

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