本文主要是介绍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
这篇关于leetcode第29题两数相除--贪心算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!