兩數相除——不容許使用高級運算

兩數相除——不容許使用高級運算

Divide Two Integers

  • 實現兩整數相除,不容許使用乘法、除法、和取餘運算。git

  • 若是結果溢出(int範圍爲-2147483648 ~ 2147483647),返回MAX_INTgithub

題目原文:ide

  • Divide two integers without using multiplication, division and mod operator.code

  • If it is overflow, return MAX_INT..ip

example leetcode

input: 1001, 2
output: 500

思路

  1. 利用減法,將被除數減去除數,減去的次數累計即爲最後結果get

  2. 爲了解決效率問題,能夠減去除數的倍數,利用位運算,每次除數左移一位(2倍),次數相應加對應的倍數。input

  3. 若是左移一位的除數過大,除數還原。it

  4. 注意處理除法運算中正負號的問題。io

代碼

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        pos = (dividend < 0) is (divisor < 0)
        dividend, divisor = abs(dividend), abs(divisor)
        result = 0
        while dividend >= divisor:
            tmp, i = divisor, 1
            while dividend - tmp >= 0:
                dividend -= tmp
                result += i
                i <<= 1
                tmp <<= 1
        if not pos:
            result = -result
        return min(2147483647, max(result, -2147483648))

本題以及其它leetcode題目代碼github地址: github地址

相關文章
相關標籤/搜索