LeetCode:29. Divide Two Integers
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.
就是实现除法。
思路
就是用减法来实现,不断减去除数。当然为了提高效率,在减去的过程中会动态增减除数。
class Solution:
def divide(self, dividend, divisor):
isMinus= ((dividend<0 and divisor >0) or (dividend>0 and divisor <0));
ret=0;
dividend,divisor=abs(dividend),abs(divisor);
c,sub=1,divisor;
while(dividend >= divisor):
if(dividend>=sub):
dividend-=sub;
ret+=c;
sub=(sub<<1);
c=(c<<1);
else:
sub=(sub>>1);
c=(c>>1);
if(isMinus):
ret=-ret;
return min(max(-2147483648,ret),2147483647);
THE END.