整数溢出
这篇我确实忽略了
if(ans>INT_MAX/10||(ans==INT_MAX/10&&temp>7))
return 0;
if(ans<INT_MIN/10||(ans==INT_MIN/10&&temp<-8))
return 0;
c++
class Solution {
public:
int reverse(int x) {
int ans=0;
int temp=0;
while(x)
{
temp=x%10;
if(ans>INT_MAX/10||(ans==INT_MAX/10&&temp>7))
return 0;
if(ans<INT_MIN/10||(ans==INT_MIN/10&&temp<-8))
return 0;
x/=10;
ans=ans*10+temp;
}
return ans;
}
};
java
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}