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

上一篇:信息学奥赛书籍 入门篇 --- 2022.01.31


下一篇:python算法和数据结构书籍(一)_ 2022.01.31