leetcode7. 整数反转

问题连接:7. 整数反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class  {
public static int reverse(int x) {
int result = 0;

while (x != 0) {
int pop = x % 10;
x = x / 10;
// 要在可能会发生溢出的操作前,对溢出进行判断
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE && pop > 7)) return 0;
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE && pop < -8)) return 0;
result = result * 10 + pop;
}
return result;
}
}