7. 整数反转

161 阅读1分钟

方法1

  • 整形int溢出的判断
  • 32位 int 表示的整数的范围是[-2147483648, 2147483647]
class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            //要在溢出前的一位进行判断
            if ((res > 214748364) || (res == 214748364 && x > 7)) {
                return 0;
            }
            //要在溢出前的一位进行判断
            if ((res < -214748364) || (res == -214748364 && x < -8)) {
                return 0;
            }
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
}

由于题目中给出的x不会越界,因此不需要判res == 214748364 && x > 7, 因为在这种情况下x就已经越界。

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