029 Divide Two Integers

029 Divide Two Integers

class Solution:
    # @param {integer} dividend
    # @param {integer} divisor
    # @return {integer}
    def divide(self, dividend, divisor):
        intMax, intMin = 2147483647, -2147483648
        if dividend==0 or divisor == 0:
            return 0
        isNeg = (dividend * divisor < 0)
        dividend, divisor = abs(dividend), abs(divisor)
        ans = 0
        tmp = 1
        d = divisor
        while dividend >= divisor:
            if dividend >= d:
                dividend -= d
                ans += tmp
                tmp += tmp
                d += d
            else:
                tmp = 1
                d = divisor
        if isNeg:
            return max(-ans, intMin)
        return min(ans, intMax)

 

posted @ 2015-08-08 14:39  dapanshe  阅读(104)  评论(0编辑  收藏  举报