模拟法
利用%运算和/运算,模拟两数反转的过程。难点在于溢出条件的判断(溢出发生于ans = ans * 10 + a阶段),在ans * 10 + a运算完成之前:
- 对于正数:
- 当ans大于max_value/10,说明当ans*10后一定溢出。
- 当ans小于max_value/10,则它+a后也不会溢出。
- 当ans等于max_value/10,在a>7时他会溢出(因为max_value%10==7)。
- 对于负数也是一样的道理。
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int a = x % 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && a > 7)) return 0;
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && a < -8)) return 0;
ans = ans * 10 + a;
x /= 10;
}
return ans;
}
}
原文:https://www.cnblogs.com/fromneptune/p/13238099.html