leetcode-29. Divide Two Integers

龍仔發表於2019-02-16

題目解析:

用加減法實現除法
用減法,每次累加被減部分,累加商, 以一個固定的倍數遞增

坑: 注意 while迴圈的跳出便捷,= 的情況要注意。
應用:累加思想,可以用在提速上,效率提高

"""

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.

"""
import time
import math
class Solution:
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        sign=(dividend>0)^(divisor>0)  #如果 ==1,則是 負的 ==0,則是正的
        dividend_current=int(math.fabs(dividend))
        divisor_current=int(math.fabs(divisor))
        quotient=0
        quotient_base=1

        while dividend_current>0:
            print(dividend_current,divisor_current,quotient)
            while dividend_current>=divisor_current:
                quotient+=quotient_base
                dividend_current-=divisor_current
                divisor_current*=2   #
                quotient_base*=2
                # time.sleep(1)
            while divisor<=dividend_current<divisor_current:
                divisor_current/=2
                quotient_base/=2
            # time.sleep(1)
            if dividend_current<divisor:
                break
        # print(sign*quotient)
        ans=int(quotient) if not sign else (-1)*int(quotient)
        if ans >= 2 ** 31:
            return 2 ** 31 - 1
        elif ans <= -2 ** 31 - 1:
            return -2 ** 31
        else:
            return ans
if __name__==`__main__`:
    st=Solution()
    dividend=128
    dividend=-2147483648
    divisor=1
    # out=st.divide(-128,3)
    out=st.divide(dividend,divisor)
    print(out)


相關文章