Skip to content

Commit ecf36e2

Browse files
committed
Add algorithm: divide two integers in bit_manipulation
1 parent e2a78d4 commit ecf36e2

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class Solution:
2+
def divide(self, dividend: int, divisor: int) -> int:
3+
"""
4+
Divide two integers without using *, /, or % operators.
5+
6+
LeetCode Problem: https://leetcode.com/problems/divide-two-integers/
7+
8+
Args:
9+
dividend (int): The number to be divided.
10+
divisor (int): The number to divide by.
11+
12+
Returns:
13+
int: The quotient after truncating toward zero.
14+
15+
Examples:
16+
>>> sol = Solution()
17+
>>> sol.divide(43, 8)
18+
5
19+
>>> sol.divide(10, 3)
20+
3
21+
>>> sol.divide(-7, 2)
22+
-3
23+
>>> sol.divide(1, 1)
24+
1
25+
>>> sol.divide(-2147483648, -1) # overflow case
26+
2147483647
27+
>>> sol.divide(24, 8)
28+
3
29+
>>> sol.divide(43, -8)
30+
-5
31+
"""
32+
# Edge case: if both are equal, result is 1
33+
if dividend == divisor:
34+
return 1
35+
36+
# Determine the sign of the result
37+
sign = not (
38+
(dividend < 0) ^ (divisor < 0)
39+
) # True if same sign, False if different
40+
41+
# Convert both numbers to positive
42+
d = abs(dividend) # remaining dividend
43+
n = abs(divisor) # divisor
44+
quo = 0 # quotient
45+
46+
# Outer loop: subtract divisor multiples from dividend
47+
while d >= n:
48+
cnt = 0
49+
50+
# Inner loop: find largest power-of-two multiple of divisor that fits in dividend
51+
while d >= (n << (cnt + 1)):
52+
cnt += 1
53+
54+
# Add this power-of-two chunk to quotient
55+
quo += 1 << cnt
56+
57+
# Subtract the chunk from remaining dividend
58+
d -= n << cnt
59+
60+
# Handle overflow for 32-bit signed integers
61+
if quo == (1 << 31):
62+
return (2**31 - 1) if sign else -(2**31)
63+
64+
return quo if sign else -quo
65+
66+
67+
if __name__ == "__main__":
68+
import doctest
69+
70+
doctest.testmod() # Run the doctest examples
71+
72+
# Optional: interactive test
73+
sol = Solution()
74+
dividend = int(input("Enter dividend: "))
75+
divisor = int(input("Enter divisor: "))
76+
print(f"Quotient: {sol.divide(dividend, divisor)}")

0 commit comments

Comments
 (0)