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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
版本1:
class Solution {
public:
int reverse(int x) {
int y= 0;
while (x > 9 || x < -9) {
y = y * 10 + x % 10;
x = x / 10;
}
if (x) { // 处理Overflow
if (y * 10 / 10 != y)
return 0;
y = y * 10;
if (y + x - x != y)
return 0;
y += x;
}
return y;
}
};
此处也说明leetcode是不进行编译优化的。
下面版本编译优化不会引起问题
版本2:
class Solution {
public:
int reverse(int x) {
int y= 0;
while (x > 9 || x < -9) {
y = y * 10 + x % 10;
x = x / 10;
}
if (x) { // 处理Overflow</span>
if (INT_MAX/10 < y || y < INT_MIN/10)
return 0;
y = y * 10;
if ((x>0 && INT_MAX-x<y) || (x<0 && INT_MIN-x>y))
return 0;
y += x;
}
return y;
}
};
检查Overflow的test case是新加的,网上一些博客写的极简的代码,已经无法通过leetcode了。比如下面代码:
int reverse(int x) {
int newN =0, left =0;
while(x != 0)
{
left = x%10;
newN = newN*10 + left;
x = x/10;
}
return newN;
}
下面代码虽然看起来有考虑Overflow,实则也通不过Overflow测试。简单通过检测符号改变是不够的,也就能拿来处理加法。
int reverse(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lastDigit = 0;
int result = 0;
bool isNeg = x>0? falsetrue;
x = abs(x);
while(x>0)
{
lastDigit = x%10;
result = result*10 + lastDigit;
x = x/10;
}
if(result<0) return -1;
if(isNeg)
result *=-1;
return result;
}
class Solution {
public:
int reverse(int x) {
bool isPositive = true;
if(x < 0){isPositive = false; x *= -1;}
long long res = 0;//为了防止溢出,用long long
while(x)
{
res = res*10 + x%10;
x /= 10;
}
if(res > INT_MAX)return 0;
if(!isPositive)return res*-1;
else return res;
}
};
它虽然用long long来防止溢出,但却栽在另一处溢处上
x *= -1
要知道 INT_MIN * -1 结果还是 INT_MIN
即
-2147483648 * -1 结果还是 -2147483648
这一点,可是大大出科了此算法作者的预料。要知道int的上限为2147483647。比下限的绝对值可小一点点。