-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathdivide_two_integers.py
More file actions
67 lines (53 loc) · 1.8 KB
/
divide_two_integers.py
File metadata and controls
67 lines (53 loc) · 1.8 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
"""
Divide two integers without using *, /, or % operators.
LeetCode Problem: https://leetcode.com/problems/divide-two-integers/
Args:
dividend (int): The number to be divided.
divisor (int): The number to divide by.
Returns:
int: The quotient after truncating toward zero.
Examples:
>>> sol = Solution()
>>> sol.divide(43, 8)
5
>>> sol.divide(10, 3)
3
>>> sol.divide(-7, 2)
-3
>>> sol.divide(1, 1)
1
>>> sol.divide(-2147483648, -1)
2147483647
>>> sol.divide(24, 8)
3
>>> sol.divide(43, -8)
-5
"""
# Edge case: if dividend equals divisor, result is 1
if dividend == divisor:
return 1
# Determine the sign of the result
sign = not ((dividend < 0) ^ (divisor < 0)) # True if same sign,
# Convert both numbers to positive
d = abs(dividend) # remaining dividend
n = abs(divisor) # divisor
quo = 0 # quotient
# Outer loop: subtract divisor multiples from dividend
while d >= n:
cnt = 0
# find largest power-of-two multiple of divisor that fits in dividend
while d >= (n << (cnt + 1)):
cnt += 1
# Add this power-of-two chunk to quotient
quo += 1 << cnt
# Subtract the chunk from remaining dividend
d -= n << cnt
# Handle overflow for 32-bit signed integers
if quo == (1 << 31):
return (2**31 - 1) if sign else -(2**31)
return quo if sign else -quo
if __name__ == "__main__":
import doctest
doctest.testmod()