Leetcode** 29. Divide Two Integers

Description: 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, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.

Link: 29. Divide Two Integers

Examples:

Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.

Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -2.

Example 3:
Input: dividend = 0, divisor = 1
Output: 0

Example 4:
Input: dividend = 1, divisor = 1
Output: 1

思路: 不能用乘除和模运算,只能加减。但是连续用被除数减除数,最后会超时,题解里面用了位运算,位运算代替了乘法 a << b,表示 a * 2的b次方。

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        MAX_INT = 2147483647
        if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0):
            sign = 1
        else:
            sign = -1
        dividend = abs(dividend)
        divisor = abs(divisor)
        res = 0
        while dividend >= divisor:
            k = 0
            tmp = divisor
            while dividend >= tmp:
                res += 1 << k
                dividend -= tmp
                tmp <<= 1
                k += 1
        if res*sign > MAX_INT:
            return MAX_INT
        return res*sign

日期: 2021-04-10 这个题目需要之后重复,标记**,感觉没有完全领会

posted @ 2021-04-10 20:48  summer_mimi  阅读(29)  评论(0编辑  收藏  举报