LeetCode的题目一般都很简短,经常要自己想各种可能的测试样例。
题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
这题坑爹的地方在于1000000003和-2^31这样的数翻转之后会溢出(返回0)。
我用的是比较low的方法,就是用long long:
int reverse(int x) {
long long n;
vector<int> digits;
long long result = 0;
long long power = 1;
n = x >= 0 ? (long long)x : -(long long)x; // -2^31简直是个特例!
while (n != 0) {
digits.push_back(n%10);
n /= 10;
}
for (int i = digits.size() - 1; i >= 0; i--) {
result += digits[i] * power;
power *= 10;
}
if (result > 2147483647) // 2^31-1
return 0;
return x >= 0 ? (int)result : -(int)result;
}
官方提供的判定溢出的方法:
To deal with overflow, inspect the current number before multiplication.
If the current number is greater than 214748364, we know it is going to overflow.
On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.