leetcode Divide Two Integers python

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        flag=-1
        if ( dividend > 0 and divisor >0 ) or ( dividend < 0 and divisor < 0 ):
            flag=1
        dividend=abs(dividend)
        divisor=abs(divisor)
        quotient=0
        while dividend >= divisor:
            k=0
            tmp=divisor
            while dividend >= tmp:
                quotient += 1 << k
                dividend -= tmp
                tmp <<=1
                k+=1
        
        if flag > 0:
            if quotient > 2147483647:
                quotient = 2147483647
            return quotient
        else:
            return -quotient

@link http://chaoren.is-programmer.com/posts/43017.html

posted @ 2015-12-01 23:25  hao.ma  阅读(162)  评论(0编辑  收藏  举报