leetcode 29. divide two integer
这题On 方法就是除法当减法,不停减去除数每次商加一。 如果用二分思想,每次用除数*2 *4 *8 16倍去和被除数直接比较,就可以减少计算次数,比如255不需要比较255次 只要先7次就可以得到255-128=127 然后用127继续比较。算法复杂度(lgn)平方
class Solution:
def divide(self,dividend,divisor):
max_int = 2147483647
if dividend ==0:
return 0
if (dividend>0 and divisor < 0) or (dividend<0 and divisor>0):
sign = -1
else :
sign =1
print sign
a= abs(dividend)
b= abs(divisor)
if a<b :
return 0
sol = 0
if a<b: return 0
tmpb=b
tmpres=1
while tmpb<<1 <=a : # 左移一个相当于double
tmpb = tmpb << 1 #此时暂时的结果和暂时的除数都要不停double
tmpres = tmpres << 1
sol= sol + tmpres
a = a -tmpb
sol = sol + self.divide(a,b)
print sol
print sign
sol = sol * sign
if sol > max_int:
return max_int
return sol
A = Solution()
print A.divide(7,-3)
非递归
class Solution:
def divide(self,dividend,divisor):
max_int = 2147483647
if dividend ==0:
return 0
if (dividend>0 and divisor < 0) or (dividend<0 and divisor>0):
sign = -1
else :
sign =1
a= abs(dividend)
b= abs(divisor)
if a<b :
return 0
sol = 0
while a>=b:
tmpres=1
tmpb=b
while tmpb<<1 <=a :
tmpb = tmpb << 1
tmpres = tmpres << 1
sol= sol + tmpres
a = a -tmpb
sol = sol * sign
if sol > max_int:
return max_int
return sol
A = Solution()
print A.divide(7,2)