虽然看起来很简单,但是还是有一点得注意。逆转之后可能比int类型大,会溢出,此时应该输出0。
题目大意:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution {
public:
int reverse(int x) {
long d=0;
int flag=0;
if(x<0)
{
flag=1;
x=0-x;//如果是负数先化成正数再处理,最后再逆转过来
}
while(x>0)
{
d*=10;
d+=x%10;
x/=10;
}
int res= d*pow(-1,flag);
return fabs(res) > INT_MAX ? 0 : res;//防止逆转之后溢出,可能正溢出或负溢出,都返回0
}
};