Day3-整数反转

题目

在这里插入图片描述

题解

题目还是很简单的,重点要考虑的是溢出问题

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++麻烦,性能还低,不推荐使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值