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
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
二货当然直接想到的是逐个相减
显而易见的超时了QAQ
想到可能操作和快速幂有点像
但是快速幂是底数一直扩大啊
然后就没深想 看了题解
MD 果不其然
底数先设置成除数,尝试能否整除,能的话翻倍,发现某一步底数太大了,好,还是一半一半的降下去
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if(divisor==0):
return 0
flag=1
if((dividend>0 and divisor<0) or (dividend<0 and divisor>0)):
flag=-1
dividend,divisor=abs(dividend),abs(divisor)
tot,p,q=0,1,divisor
while(dividend>=divisor):
if(dividend>=q):
tot=tot+p
dividend=dividend-q
p=(p<<1)
q=(q<<1)
else:
p=(p>>1)
q=(q>>1)
return min(max(-2147483648,tot*flag),2147483647);