编程语言
首页 > 编程语言> > leetcode第29题两数相除--贪心算法

leetcode第29题两数相除--贪心算法

作者:互联网

class Solution(object):
    def divide(self, dividend, divisor):
        Min_Int=-2 ** 31
        Max_Int=2**31-1
        times=1
        Divisor2Quotient=[]
        sign=1
        if dividend<0:sign=-1
        if divisor<0:sign=sign*-1
        divisor=abs(divisor)
        dividend=abs(dividend)
        power = divisor
        while (power<=dividend) :
            Divisor2Quotient.append([times,power])
            times+=times
            power+=power
        ans=0
        for Quotient_part,subtrahend_part in Divisor2Quotient[::-1]:
            if (dividend-subtrahend_part<0):
                pass
            else:
                dividend-=subtrahend_part
                ans+=Quotient_part
        ans=ans*sign
        if ans<Min_Int:ans=Min_Int
        elif ans>Max_Int:ans=Max_Int
        return ans

标签:--,Max,31,相除,Int,ans,两数
来源: https://blog.csdn.net/lxhseph/article/details/122673960