Reverse Integer
Soluton 1
本题主体部分和进位加法的按位实现类似,但是额外的问题是本体需要额外判断数字是否出现整型数溢出。因此需要在真的变成溢出数之前判断这个数是否真的会溢出
- 时间复杂度: O ( n ) O(n) O(n), n n n为数字的位数
- 空间复杂度: O ( 1 ) O(1) O(1),因为只有固定个数个状态变量需要维护
class Solution {
public:
int reverse(int x) {
int ans = 0;
// cout << INT_MIN << endl;
while (x != 0) {
int current = x % 10;
x /= 10;
// 有可能溢出,先检查再真的相加
if ((ans > INT_MAX / 10) || (ans == INT_MAX / 10 && current > 7)) {
// cout << ans << " " << current << endl;
return 0;
}
if ((ans < INT_MIN / 10) || (ans == INT_MIN / 10 && current < -8)) {
// cout << ans << " " << current << endl;
return 0;
}
ans = ans * 10 + current;
}
return ans;
}
};
Solution 2
本问题的Python实现。本题的一个需要注意的点是a // b
的向下取整的特性,对正数不存在问题,但是对负数,向下取整意味着绝对值加1。Python的取余实现为r = a - n * [a // n]
,因此对于负数需要额外考虑。因此在本题的情境中,对负数的取余操作的除数应为-10
而非10
。
class Solution:
def reverse(self, x: int) -> int:
ans = 0
# print(13 // 10, 13 // -10)
while x != 0:
if x < 0:
current = x % -10
else:
current = x % 10
x = int(x / 10)
ans = int(ans * 10) + current
# print(x, current, ans)
# python 整型数不存在上下界
if ans >= 2**31 - 1 or ans <= -2 ** 31:
# print(-2 ** 31, ans)
return 0
return ans