运用一般的循环减法,会超时。
运用按位左移的方法,实在是妙!值得细细体会
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if divisor == 0 or dividend == 0:
return 0
if (dividend < 0 and divisor < 0) or (dividend > 0 and divisor > 0):
flag = True
else:
flag = False
if dividend == -2147483648 and divisor == -1:
return 2147483647
if divisor == 1:
return dividend
dividend = abs(dividend)
divisor = abs(divisor)
count = 0
for i in reversed(range(31)):
cur = divisor << i
if dividend >= cur:
count |= 1 << i
dividend = dividend - cur
# print(i, dividend, divisor)
if not flag:
count = 0 - count
return count
网友评论