题目
题解
题目还是很简单的,重点要考虑的是溢出问题
C++
错解
class Solution {
public:
int reverse(int x) {
int res=0;
while(x)
{
res=res*10+x%10;
x=x/10;
}
return res;
}
};
当输入为1534236469时,整数反转以后会溢出
报错: runtime error: signed integer overflow: 964632435 * 10 cannot be represented in type ‘int’
正解
首先想的是把res变量变成long int型的,但是题目规定了32位有符号整数,所以该方法不可取
在反转时加一个判断条件,溢出则返回0
溢出情况:
7的来由:7= INTMAX %10
-8的来由:-8= INTMIN %10
class Solution {
public:
int reverse(int x) {
int max=pow(2,31)-1;//int的最大值
int min=pow(-2,31);//int的最小值
int res=0;
while(x)
{
//溢出判断
if(res>max/10 || (res==max/10 && x%10>7) )
return 0;
if(res<min/10 || (res==min/10 && x%10<-8))
return 0;
res=res*10+x%10;
x=x/10;
}
return res;
}
};
pyhton
注意:python的取模是根据向下取整法的,而c/c++/java是基于向零取整的,即在python中 -1%10=-9,因此算法和c++也略有不同,需要正负数分开考虑
class Solution(object):
def reverse(self, x):
res=0
y=abs(x) # y是x的绝对值
max=2**31-1
min=-(-2)**31
while y:
# 溢出判断
# 正数
if x>0 and (res>max//10 or (res==max//10 and y%10>7)):
return 0
# 负数
if x<0 and (res>min//10 or (res==min//10 and y%10>8)):
return 0
res=res*10+y%10
y=y//10
if x>0:
return res
else:
return -res
性能对比
从这道题来看,python要比c++麻烦,性能还低,不推荐使用