leetcode-29. Divide Two Integers

题目解析:

用加减法实现除法
用减法,每次累加被减部分,累加商, 以一个固定的倍数递增

坑: 注意 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)


    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000015913188
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞