Skip to content
Open
Changes from 1 commit
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
Prev Previous commit
Add divide function for two integers
Implement division of two integers using bit manipulation and handle edge cases.
  • Loading branch information
mihika632 authored Oct 4, 2025
commit 3d8dd884aeb384dd11cdda081229e30765ba938b
47 changes: 47 additions & 0 deletions Python/29_divideTwoIntegers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
"""
Approach:
- Handle edge case: overflow when dividend = -2^31 and divisor = -1
- Work with absolute values to simplify calculation.
- Use bit manipulation (left shifts) to speed up repeated subtraction:
- Keep doubling the divisor until it exceeds dividend.
- Subtract the largest multiple of divisor from dividend and accumulate quotient.
- Apply sign at the end based on the input signs.

Intuition:
- Division is repeated subtraction.
- Using bit shifts allows us to subtract large chunks at once, reducing complexity from O(n) to O(log n)^2.

Time Complexity: O(log(dividend)^2), because we double the divisor each time and subtract in a loop.
Space Complexity: O(1), only constant extra variables are used.
"""
# 32-bit integer limits
INT_MAX = 2**31 - 1
INT_MIN = -2**31

# Edge case for overflow
if dividend == INT_MIN and divisor == -1:
return INT_MAX

# Determine the sign of the result
negative = (dividend < 0) != (divisor < 0)

# Work with absolute values
dividend, divisor = abs(dividend), abs(divisor)
quotient = 0

# Repeated subtraction using bit shifts
while dividend >= divisor:
temp_divisor, multiple = divisor, 1
while dividend >= (temp_divisor << 1):
temp_divisor <<= 1
multiple <<= 1
dividend -= temp_divisor
quotient += multiple

# Apply sign
if negative:
quotient = -quotient

return quotient