题目描述
自己解法
很无脑的解法,先转成字符串再进行判断,Python代码:
class Solution:
def reverse(self, x: int) -> int:
x = str(x)
if not x[0].isnumeric(): #负数
x = x[0] + x[1:][::-1]
pos = 0
for i in range(1,len(x)):
if x[i] != '0':
pos = i
break
x = x[0] + x[pos:]
if int(x) < -math.pow(2,31):
return 0
else:
x = x[::-1]
pos = 0
for i in range(len(x)):
if x[i] != '0':
pos = i
break
x = x[pos:]
if int(x) > math.pow(2,31) - 1:
return 0
return int(x)
官方题解
直接在原数字上进行转换,进行取余和相除操作,逐步获取低位数字,详见:官方解答。
C++代码:
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
};