题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
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.
思路
- 如果用long保存结果,将结果与INT_MAX比较,返回的时候将long转换为int,则这道题解法将十分简单,代码也少。
- 可是如果限定了只能用int存储数值,中间没有任何long到int的转换或者负数到正数的转换,那么还是比较有挑战性的。
代码
class Solution {
public:
int reverse(int x) {
int res{0};
if (x >= 0)
{
do {
if (res > (INT_MAX - x%10)/10) return 0;
res = (res<<3) + (res<<1) + x%10;
//res = res * 10 + x % 10;
}while (x /= 10);
}
else
{
do {
if (res < (INT_MIN - x%10)/10) return 0;
res = (res<<3) + (res<<1) + x%10;
//res = res * 10 + x % 10;
}while (x /= 10);
}
return res;
}
};
这段代码运用了一个很巧妙的方法来判断乘法溢出问题:
res > (INT_MAX - x%10)/10
……………………………….(1)
一般的想法是直接判断 if (res > INT_MAX)
,但这是有问题的,因为即使运算过程中发生了溢出,结果也永远都小于INT_MAX,所以这个判断是无效的。怎么办呢?将res与缩小了10倍的INT_MAX作比较!将上面的(1)式作变换 res * 10 + x%10 > INT_MAX,可以看到它成功的判断了res = res * 10 + x%10是否大于INT_MAX.
当x<0时,和上面类似,判断if (res < (INT_MIN - x%10)/10)
就知道是否出现下溢。这里有一点要注意的是负数取余的结果是负数,所以才能res = res * 10 + x % 10,否则res将是正数。