- 判断是否overflow的部分注意:
- 根据x的正负检测。
- 根据result不准确,我们需要检测x还剩一位数的时候result是否overflow
Implementation
public class Solution {
public int reverse(int x) {
int result = 0;
final int MIN_THRESHOLD = Integer.MIN_VALUE / 10;
final int MAX_THRESHOLD = Integer.MAX_VALUE / 10;
while (x != 0) {
int newResult = result * 10 + x % 10;
x = x / 10;
if (x > 0 && (newResult > MAX_THRESHOLD || (newResult == MAX_THRESHOLD && x > 7)))
return 0;
if (x < 0 && (newResult < MIN_THRESHOLD || (newResult == MIN_THRESHOLD && x < -8)))
return 0;
result = newResult;
}
return result;
}
}
public class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int newResult = result * 10 + x % 10;
x = x / 10;
if (newResult / 10 != result) {
return 0;
}
result = newResult;
}
return result;
}
}