Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3 Output: 3
Example 2:
Input: dividend = 7, divisor = -3 Output: -2
不用乘除取余的操作符号,完成一个除法操作。
以往判断符号直接两数相乘判断,这里用 is 方法。然后将两数取绝对值。
然后就是一个不断减除数的一个过程,为了加速,每次将除数左移一位(相当于×2),然后类似于tcp中快恢复算法,重复这个过程。
最后要判断是否在[−2^31, 2^31 − 1]范围内。
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
sym= (dividend<0) is (divisor<0)
dividend, divisor = abs(dividend), abs(divisor)
res=0
while dividend>=divisor:
index=1
ndivisor=divisor
while dividend>=ndivisor:
dividend -= ndivisor
res+=index
index<<=1
ndivisor<<=1
if not sym:res=-res
return max(min(res,2147483647),-2147483648)