总的来说是减法没错,但是一个一个减去时间一定会超,所以做法是减去1倍,2倍, 4倍,没办法减以后再从1倍开始。
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
positive = (dividend < 0) is (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
res = 0
while dividend >= divisor:
temp, i = divisor, 1
while dividend >= temp:
dividend -= temp
res += i
i = i << 1
temp = temp << 1
if not positive:
res = -res
return min(max(-pow(2,31), res),pow(2,31)-1)
网友评论