LeetCode——Reverse Integer
Leedcode第七题:
题目如下:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
class Solution {
public:
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
long res = 0;
while(x)
{
res = res*10 + x%10;
x /= 10;
}
return res;
}
};
然后提交后就出现了Wrong Answer
Input: | 1534236469 |
Output: | 1056389759 |
Expected: | 0 |
在于没有考虑溢出处理
修改后的代码:
class Solution{
public:
int reverse(int x) {
bool negative=false;//是否为负数
if(x==INT_MIN) //这里必须要判断 应为INT_MIN为了表示方便用八位 二进制为 1000 0000 进行x=-x运算时,计算机中用补码相乘,-1的补码为原码除符号位外取反加1 也就是 1000 0001 取反加一补码变为 1111 1111,所以x=-x变为补码乘法 1000 0000*1111 1111 =1000 0000,x又等于了INT_MIN ,所以当while循环中的x并没有为正数。
return 0;
if(x<0)
{
x=-x;
negative_flag=true;
}
long long result=0;
while(x!=0)
{
result=result*10+x%10;
x=x/10;
}
if(result>INT_MAX)
return 0;
if(negative)
return -result;
else
return result;
}
}
这里COPY了网友的注解http://www.2cto.com/kf/201501/370484.html,实在没想到x==INT_MIN的情况 看似简单的题目其实暗藏危机 ,难怪通过率并不高