Divide Two Integers

英文原题

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<=2**31-1 else ans
        else:
            return -2**31 if -ans<=-2**31 else -ans

你可能感兴趣的:(Divide Two Integers)