python leetcode 29. Divide Two Integers
阿新 • • 發佈:2018-12-08
注意while迴圈中的加速操作
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
a=abs(dividend)
b=abs(divisor)
if a<b:
return 0
count=0
res= 0
while a>=b:
d=b
count=1
while d+d<=a:
d+=d
count+=count
a-=d
res+=count
if (dividend > 0 and divisor < 0 ) or (dividend < 0 and divisor > 0):
res=0-res
if res> 2**31-1:
return 2**31-1
elif res<-2**31:
return -2**31
else:
return res