7. Reverse Integer
- 溢出检查
题目
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
思路
遍历存储。
直接遍历倒序存储数组,然后乘相应的幂次再相加。复杂性分析:
- 时间复杂度:O(n).
- 空间复杂度:O(1).
题解
class Solution {
public:
int reverse(int x) {
bool neg = false;
if (x < 0) neg = true;
int temp = abs(x);
vector<int> ansArr;
while (temp) {
ansArr.push_back(temp%10);
temp = temp/10;
}
long long ans = 0;
for (int i = 0; i < ansArr.size(); i++) {
ans += ansArr[i] * pow(10, ansArr.size()-i-1);
}
if (neg) ans *= -1;
if (ans > pow(2, 31)-1 || ans < pow(2, 31)*-1) return 0;
return ans;
}
};
反思
- 注意越界的情况。
因为限定为32位的有符号整数,所以在求倒序数时用 int 类型存储很容易出现越界导致答案错误。所以应该先使用64位 long long 类型的有符号长整数存储后,判断是否越界,再决定返回值。
优化代码
class Solution {
public:
int reverse(int x) {
int y=0;
int n;
while( x != 0){
n = x%10;
// 在运算过程中做溢出检查
if (y > INT_MAX/10 || y < INT_MIN/10){
return 0;
}
y = y*10 + n;
x /= 10;
}
return y;
}
};