示例 :
輸入: dividend = 10, divisor = 3
輸出: 3
題解:22除以3,2大于3所以結(jié)果至少為1宗收,22大于3的翻倍6所以結(jié)果至少為2漫拭,22大于6的翻倍12所以結(jié)果至少為4,22小于12的翻倍所以被除數(shù)改為22-12=10,遞歸運算。
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend == 0:
return 0
if divisor == 1:
return dividend
if divisor == dividend:
return 1
if dividend == -pow(2,31) and divisor == -1:
return pow(2,31)-1
flag = 1
if dividend <0 and divisor > 0:
divisor = -divisor
flag = -1
elif dividend > 0 and divisor < 0:
dividend = -dividend
flag = -1
elif dividend > 0 and divisor > 0:
dividend = -dividend
divisor = -divisor
def div(a, b):
if a - b > 0:
return 0
else:
cnt = 1
tb = b
while tb + tb > a:
cnt = cnt + cnt
tb = tb + tb
return cnt + div(a-tb, b)
cnt = div(dividend, divisor)
return -cnt if flag<0 else cnt