简繁EN

LeetCodeNo. 119

[LeetCode with Python] 29. Divide Two Integers

Contents

Problem

Problem page: https://leetcode.com/problems/divide-two-integers/
Topics: Math, Binary Search
Difficulty: Medium

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

If it is overflow, return MAX_INT.


Analysis

The problem doesn't allow multiplication, division or modulo, so I just use shifts, addition and subtraction. I keep track of the sign separately and use absolute values in the loop. I keep doubling the divisor by shifting it left one bit each time, and I double sub_result along with it to keep track of the multiple. Once another doubling would exceed the remaining dividend (dividend_now), I subtract the shifted divisor from it and add sub_result to result. If dividend_now is still at least as big as the original divisor, I go another round. I just drop the final remainder since it's smaller than the divisor, so the result is truncated toward zero.

Both inputs are 32-bit signed integers. Dividing by 1 leaves the dividend unchanged. A divisor with an absolute value of at least 2 gives a quotient with an absolute value of at most 1073741824, so neither case overflows. Dividing by -1 negates the dividend, and only -2147483648 becomes 2147483648, which is outside the 32-bit signed integer range. The problem says to return MAX_INT on overflow. Python integers don't overflow on their own, so I have to check for this case myself or I'll return that out-of-range result.

After each subtraction, the remaining dividend is smaller than the number I just subtracted, so the next round takes at least one fewer doubling. With q as the absolute value of the quotient, I get at most about log q rounds. Even the longest round takes at most about log q doublings, so the time complexity is O(log² q).


Code

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

Article link: https://xnerv.wang/en/leetcode-divide-two-integers/