Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions bit_manipulation/divide_two_integers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
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) # overflow case
2147483647
>>> sol.divide(24, 8)
3
>>> sol.divide(43, -8)
-5
"""
# Edge case: if both are equal, result is 1
if dividend == divisor:
return 1

# Determine the sign of the result
sign = not (
(dividend < 0) ^ (divisor < 0)
) # True if same sign, False if different

# 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

# Inner loop: find largest power-of-two multiple of divisor that fits in dividend

Check failure on line 50 in bit_manipulation/divide_two_integers.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

bit_manipulation/divide_two_integers.py:50:89: E501 Line too long (93 > 88)
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() # Run the doctest examples

# Optional: interactive test
sol = Solution()
dividend = int(input("Enter dividend: "))
divisor = int(input("Enter divisor: "))
print(f"Quotient: {sol.divide(dividend, divisor)}")
Loading