我认为1534236469超出范围! Leetcode:7.反向整数 我无法通过测试输入1534236469。为什么?返回范围为[Integer.MAX_VALUE,Integer.MIN_VALUE],其他应返回零
class Solution {
public int reverse(int x) {
if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
return 0;
int ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
return ans;
}
}
感谢您的帮助
答案 0 :(得分:5)
1534236469
的倒数为9646324351
,比Integer.MAX_VALUE
大,因此您的代码将导致数字溢出和错误的结果。
您可以使用long
而不是int
来解决问题。
编辑:
您添加的if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE)
条件毫无意义,因为x
是int
,所以它永远不会超出int
s的有效范围。
即使x
在有效范围内,x
的倒数也可能在范围之外。如果要检测到反转的x
太大并返回0,则应在内部使用long
:
class Solution {
public int reverse(int x) {
long ans = 0;
while(x != 0) {
ans = ans * 10 + (x % 10);
x /= 10;
}
if(ans > Integer.MAX_VALUE) {
return 0;
} else {
return (int) ans;
}
}
}