第二次
class Solution
{
public:
int reverse(int x) {
if (overflow(x))
return 0;
return reverseIter(0, x);
}
private:
bool overflow(int x) {
// The number between [-1e9, 1e9] will not cause overflow after reversion.
if (x >= -1e9 && x <= 1e9)
return false;
else if (x == INT_MIN)
return true;
// 7463847412 -> 2147483647
// or -8463847412 -> -2147483648
// Given an integer x, say its digits is like {x0, x1, ..., x9}
// 1. The x0 must be 1 or 2, or it will return false before the program runs here
// 2. We only have to consider the relationship between {x1, ..., x9} and 463847412, which is reverse by the lower digits of INT_MAX
x = abs(x);
int bound = reverseIter(0, INT_MAX / 10);
for (int num = bound; num != 0; num /= 10, x /= 10)
if (x % 10 > num % 10)
return true;
else if (x % 10 < num % 10)
return false;
return false;
}
inline int reverseIter(int res, int x) {
if (x == 0)
return res;
else
return reverseIter(res * 10 + x % 10, x / 10);
}
};
第一次
上界2147483647-, 下界2147483648. 反过来看7463847412 -> 2147483647, -8463847412 -> -2147483648
为使反转不越界,那么绝对值大于10^9的参数x的前9位应满足<=463847412. 我们没有考虑最高位,是因为最高位一定<=2, 从而<=7或8
所以反转前先检查是否将溢出,溢出时返回-1; 反之开始反转。
代码:
class Solution
{
public:
int reverse(int x)
{
if( overflow(x) == true)
{
return -1;
}
int ret = 0;
while (x!=0)
{
ret = 10*ret + x%10;
x /= 10;
}
return ret;
}
private:
bool overflow(int x)
{
if (x / 1000000000 == 0) // x的绝对值小于1000000000, 不越界
{
return false;
} else if (x == INT_MIN) // INT_MIN反转后越界,也没法按下述方法取绝对值(需要特判),直接返回true
{
return true;
}
x = abs(x);
// x = d463847412 -> 2147483647. (参数x,本身没有越界,所以d肯定是1或2)
// or -d463847412 -> -2147483648.
for (int cmp = 463847412; cmp != 0; cmp/=10, x/=10)
{
if ( x%10 > cmp%10 )
{
return true;
} else if (x%10 < cmp%10)
{
return false;
}
}
return false;
}
};