个人LeetCode刷题记录:7. 整数反转
题目地址
java求解代码
class Solution
{
public int reverse(int x)
{
int res = 0; //记录最后返回的结果值
int t ; //用来临时记录
while(x != 0) //因为x可取正负,不适合用x>0,或x<0,每次提取x最后一位,x为0意味着x每一位数被提取完
{
t = x % 10;
if( res > Integer.MAX_VALUE / 10 ||( res == Integer.MAX_VALUE / 10 && t == 7))return 0;
if( res < Integer.MIN_VALUE / 10 ||( res == Integer.MIN_VALUE / 10 && t == -8))return 0;
res = res * 10 + t;
x = x / 10;
}
return res;
}
}
本题重点:越界检测
四种情况
- 当出现 res > MAX_VALUE / 10 且 还有 t 需要添加时,则一定溢出
- 当出现 res == MAX_VALUE / 10 且 t > 7 时,则一定溢出(7是2^31 - 1 = 2147483647的个位数)
- 当出现 res < MIN_VALUE / 10 且 还有 t 需要添加时,则一定溢出
- 当出现 res == MIN_VALUE / 10 且 t < -8 时,则一定溢出(8是-2^31 = -2147483648的个位数)
需注意的细节
不同编程语言的负数取模运算规则不一定相同
比如:
java:(-7) % 3 = - 1
python : (-7) % 3 = 2