注意處理overflow和negative的問題。
class Solution {
public:
int reverse(int x) {
bool positive = (x>=0);
x = abs(x);
int result = 0;
for(; x; x/=10)
{
result = result*10 + x%10;
}
if(result < 0)
return -1;
return positive?result:(0-result);
}
};
class Solution {
public:
int reverse(int x)
{
bool negative = (x<0);
if(x < 0) x = 0-x;
if(x < 0) return 0;
int result = 0;
while(x != 0)
{
if(result > INT_MAX/10)
return 0;
if(result == INT_MAX/10 && (x%10) > (INT_MAX%10))
return 0;
result = result*10+(x%10);
x /= 10;
}
return negative?(0-result):(result);
}
};