美文网首页
Divide Two Integers

Divide Two Integers

作者: Kong_Mt | 来源:发表于2019-05-18 01:56 被阅读0次

    英文原题

    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
    

    中文原题

    给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。返回被除数 dividend 除以除数 divisor 得到的商。

    题解

    class Solution(object):
        def divide(self, dividend, divisor):
            """
            :type dividend: int
            :type divisor: int
            :rtype: int
            """
            dd=abs(dividend)
            ds=abs(divisor)
            flag=abs(dividend+divisor)==dd+ds
            ans=0
            for i in range(31,-1,-1):
                if dd>>i>=ds:
                    ans+=1<<i
                    dd-=ds<<i
            if flag:
                return 2**31-1 if ans>=2**31-1 else ans
            else:
                return -2**31 if -ans<=-2**31 else -ans
    

    相关文章

      网友评论

          本文标题:Divide Two Integers

          本文链接:https://www.haomeiwen.com/subject/nwczaqtx.html