解法1: 不用64为整数,需要判断中间结果abs(res) 是否超过INT_MAX / 10,若是说明越界,返回0. 解法2:虽然不符合题意,但对于有64位整数的环境。直接循环翻转就行。只需把res定义为long类型,方便处理超出整形范围的数。负数也不用特殊处理。
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x != 0) {
if (abs(res) > INT_MAX / 10) {
return 0;
}
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
};
class Solution {
public:
int reverse(int x) {
long res = 0;
while (x != 0) {
auto rem = x % 10;
x /= 10;
res = res * 10 + rem;
}
if (res > INT_MAX || res < INT_MIN) {
return 0;
}
return res;
}
};
class Solution:
def reverse(self, x: int) -> int:
INT_MIN = -2 ** 31
INT_MAX = 2 ** 31 - 1
if INT_MIN < x < INT_MAX and x != 0:
result = int((str(x) if x > 0 else str(-x) + "-")[::-1])
return result if -2 ** 31 < result < 2 ** 31 - 1 else 0
else:
return 0