简繁EN

LeetCodeNo. 119

【LeetCode with Python】 29. Divide Two Integers

目錄

題目

原題頁面:https://leetcode.com/problems/divide-two-integers/
題目型別:Math, Binary Search
難度評價:Medium

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

If it is overflow, return MAX_INT.


分析

題目不讓用乘法、除法和取模,所以我只用移位和加減來算,正負號單獨記下,迴圈裡都用絕對值算。演算法用倍增:把除數不停地左移一位,sub_result跟著翻倍記下是幾倍,直到再翻一次就會超過剩下的被除數dividend_now;這時從dividend_now裡減掉翻倍後的除數,把sub_result加進result,dividend_now還不小於原來的除數就再來一輪。最後剩下的餘數小於除數,直接丟掉,所以結果是向零截斷的。

兩個輸入都是32位有符號整數,會溢位的只有-2147483648除以-1:除數是1時商就是被除數,除數的絕對值至少是2時商的絕對值不超過1073741824,都不會超範圍,而除數是-1時商是被除數取負,只有-2147483648取負得到的2147483648超出了32位有符號整數,題目要求溢位時返回MAX_INT。Python的整數不會自己溢位,所以這種情況得自己判斷,不然返回的就是那個超出範圍的結果。每輪減完,剩下的被除數比剛減掉的數小,所以下一輪翻倍的次數至少少一次。輪數和每輪翻倍的次數都最多大約log q(q是商的絕對值),乘起來時間複雜度就是O(log² q)。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution:
# @return an integer
def divide(self, dividend, divisor):

if 0 == divisor or 0 == dividend:
return 0
elif 1 == divisor:
return dividend
elif -1 == divisor:
# -(-2147483648) does not fit in 32 bits, return MAX_INT
return 2147483647 if -2147483648 == dividend else -dividend

positive = 1
if (dividend >0 and divisor < 0) or (dividend < 0 and divisor > 0):
positive = -1
dividend = dividend if dividend > 0 else -dividend
divisor = divisor if divisor > 0 else -divisor

result = 0
dividend_now = dividend
while dividend_now >= divisor:
total = divisor
sub_result = 1
while True:
total = total << 1
sub_result = sub_result << 1 ## not += 2
if total > dividend_now:
total = total >> 1
sub_result = sub_result >> 1
break
elif total == dividend_now:
break
result += sub_result
dividend_now -= total
return result if 1 == positive else -result

本文地址:https://xnerv.wang/zh-tw/leetcode-divide-two-integers/