29. 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

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: [−2^31,  2^31 − 1]. For the purpose of this problem, assume that your function returns 2^31 − 1 when the division result overflows.

这题提示不能用乘法,除法,取余,所以可以用的是可以用加法,减法, >>1, <<1的位运算。

因为只能用位运算代替乘除,所以我们用2的幂次来组成结果。从最大头的部分开始,之后减去后,依次求解。这题另外提示可能会overflow所以要处理边界问题,能出现2^ 31的情况只有被除数为:

-2^31,除数为-1的情况(The divisor will never be 0)。代码如下:

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        int_max = 2**31-1
        int_min = -2**31
        if divisor == 0 or (dividend == int_min and divisor == -1):
            return int_max
        sign = 1 if ((dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0)) else -1 
        
        divid = abs(dividend)
        divis = abs(divisor)
        
        res = 0
#注意这里要保存为相等,防止开始被除数和除数相等的情况
while divid >= divis: cur = divis cnt = 1
#处理整除的情况 while cur <= divid: cur = cur << 1 cnt = cnt << 1 res += cnt >> 1 divid -= cur >> 1 if sign > 0: return res else: return -res

注意代码对整除,被除数和除数相等的情况要做下处理,所以要保存等号

posted on 2018-10-02 11:49  Sheryl Wang  阅读(84)  评论(0编辑  收藏  举报

导航