前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[Leetcode]29. Divide Two Integers @python

[Leetcode]29. Divide Two Integers @python

作者头像
蛮三刀酱
发布2019-03-26 15:34:58
8780
发布2019-03-26 15:34:58
举报

题目

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

题目要求

除法运算,但是不能用编程语言提供的乘法、除法和取模运算,即只能用加法和减法实现。

解题思路

为了加速运算,可以依次将被除数减去1,2,4,8,..倍的除数。所以这里可以用移位来进一步加速。本方法参考了kitt的博文。另外需要注意的是溢出问题。因为Python本身是没有溢出问题的,所以需要在最后判断,结果是否溢出,如果溢出则要返回MAX_INT

代码

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        MAX_INT = 2147483647
        sign = 1 if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else -1
        quotient = 0
        dividend = abs(dividend)
        divisor = abs(divisor)
        while dividend >= divisor:
            k = 0
            tmp = divisor
            while dividend >= tmp:
                dividend -= tmp
                quotient += 1 << k
                tmp <<= 1
                k += 1
        quotient  = sign * quotient
        if quotient > MAX_INT:
            quotient = MAX_INT
        return quotient
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年01月16日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题目要求
  • 解题思路
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档