如果没有判溢,这道题其实非常简单,但是部分10位数倒过来会超过int的范围,比如这个测试用例-2147483648=-2^31,即80000000,取补码还是本身,,我本来想做一个取反工作,结果在过这个测试用例的时候就傻了。
if(x<0)
{
flag = -1;
x = x / 10;
x = -x;//x = -2147483648
}
最终代码:
#include<iostream>
using namespace std;
class Solution1 {
public:
int reverse(int x) {
//int flag = 1;
int y = 0;
/*if(x<0)
{
flag = -1;
x = x / 10;
x = -x;//x = -2147483648
}*/
do
{
if (y > INT_MAX/10||y<INT_MIN/10)
{
return 0;
}
y = y * 10 + x % 10;
x = x / 10;
}
while(abs(x) > 0);
//return flag*y;
return y;
}
};
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
if (rev < INT_MIN / 10 || rev > INT_MAX / 10) {
return 0;
}
int digit = x % 10;
x /= 10;
rev = rev * 10 + digit;
}
return rev;
}
};
int main()
{
Solution1 test;
int x = -2147483648;
cout << test.reverse(x)<<endl;
}