思路一:暴力
不用想肯定超时间
def divide(dividend: int, divisor: int) -> int:
flag = 1
if dividend * divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
flag = -1
elif dividend < 0 and divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
count = 0
while dividend >= divisor:
dividend -= divisor
count+=1
return flag * count
思路二:除数累加
基于暴力的思路,反正是减法,要让余数小于除数,所以每一次可以检查一下被除数是否大于现在的除数的两倍,如果可以的话,可以直接将除数2,目前的商2,
如果不大于的话,我第一次想的是剩下的被除数再一个个减除数,但是这样还是爆时间(可以想一下为什么)
先来个错误的代码:
def divide( dividend: int, divisor: int) -> int:
flag = 1
if dividend * divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
flag = -1
elif dividend < 0 and divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
count = 0
new_divisor = divisor
if dividend >= divisor:
dividend -= divisor
count += 1
while dividend >= divisor:
if (dividend - 2*new_divisor) >= divisor:
count += count
dividend -= new_divisor
new_divisor += new_divisor
else:
dividend -= divisor
count+=1
return flag * count
其实每一次都可以从1开始倍增,这样也就引出了好用的位运算
def divide( dividend: int, divisor: int) -> int:
#边界条件
if dividend == -2**31 and divisor == -1:
return 2**31 - 1
# 控制正负
flag = 1
if dividend * divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
flag = -1
elif dividend < 0 and divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
count = 0
new_divisor = divisor
if dividend >= divisor:
dividend -= divisor
count += 1
# 需要每次都利用上递加
while dividend >= divisor:
new_divisor = divisor
temp_count = 1
while (dividend - 2*new_divisor) >= divisor:
temp_count += temp_count
new_divisor += new_divisor
dividend -= new_divisor
count += temp_count
return flag * count
思路三:位运算
按照上面的思路,其实下面的位运算很好理解,思路是一样的,只是递加换成了位运算,同时避免了乘法
def divide( dividend: int, divisor: int) -> int:
if dividend == -2**31 and divisor == -1:
return 2**31 - 1
flag = 1
if dividend * divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
flag = -1
elif dividend < 0 and divisor < 0:
dividend = abs(dividend)
divisor = abs(divisor)
count = 0
for i in range(31,-1,-1):
if (divisor << i) <= dividend:
dividend -= divisor << i
count += 1 << i
return flag * count