Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
提示中告诉我们需要关注的几个问题:
负数:实际上如果我们考虑使用模10运算的时候,并不需要考虑负数的情况。由于-123 % 10 = -3,因此无需特殊考虑负数。
溢出:溢出是我们要对结果在倍乘之前考虑,否则在倍乘之后,就会出现溢出,数据就没有意义了。
class Solution {
public:
int reverse(int x) {
int res=0;
while(x!=0)
{
if(res>INT_MAX/10||res<-INT_MAX/10)
return 0;
res=res*10+x%10;
x=x/10;
}
return res;
}
};