[leetcode]Divide Two Integers @ Python


原題地址:https://oj.leetcode.com/problems/divide-two-integers/

題意:Divide two integers without using multiplication, division and mod operator.

解題思路:不許用乘、除和求余實現兩數的相除。那就只能用加和減了。正常思路是被除數一個一個的減除數,直到剩下的數比除數小為止,就得到了結果。這樣是無法ac的,因為時間復雜度為O(n),比如一個很大的數除1,就很慢。這里我們可以用二分查找的思路,可以說又是二分查找的變種。

代碼:

class Solution:
    # @return an integer
    def divide(self, dividend, divisor):
        if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
            if abs(dividend) < abs(divisor):
                return 0
        sum = 0; count = 0; res = 0
        a = abs(dividend); b = abs(divisor)
        while a >= b:
            sum = b
            count = 1
            while sum + sum <= a:
                sum += sum
                count += count
            a -= sum
            res += count
        if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
            res = 0 - res
        return res

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM