#29
Divide Two Integers
MediumMathBit ManipulationBit ManipulationMathGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Bit Manipulation)★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
The optimal approach uses bit manipulation to perform division more efficiently. By leveraging the properties of binary numbers, we can double the divisor and count how many times it fits into the dividend, which reduces the number of iterations significantly.
⚙️
Algorithm
6 steps- 1Step 1: Handle edge cases for overflow.
- 2Step 2: Determine the sign of the quotient based on the signs of dividend and divisor.
- 3Step 3: Work with positive values of dividend and divisor.
- 4Step 4: Use a loop to double the divisor and a counter to track how many times it fits into the dividend.
- 5Step 5: Subtract the largest doubled divisor from the dividend and add to the quotient accordingly.
- 6Step 6: Return the quotient, ensuring it is within the 32-bit signed integer range.
solution.py19 lines
1# Full working Python code with comments
2
3def divide(dividend: int, divisor: int) -> int:
4 # Edge case for overflow
5 if dividend == -2**31 and divisor == -1:
6 return 2**31 - 1
7 # Determine the sign of the quotient
8 sign = -1 if (dividend < 0) ^ (divisor < 0) else 1
9 # Work with positive values
10 dividend, divisor = abs(dividend), abs(divisor)
11 quotient = 0
12 while dividend >= divisor:
13 temp, multiple = divisor, 1
14 while dividend >= temp:
15 dividend -= temp
16 quotient += multiple
17 temp <<= 1 # Double the temp
18 multiple <<= 1 # Double the multiple
19 return sign * quotientℹ
Complexity note: The time complexity is O(log n) because we are effectively halving the dividend in each iteration by doubling the divisor, which reduces the number of iterations significantly compared to the brute force approach.
- 1Recognizing that division can be simulated through repeated subtraction or bit manipulation can help in optimizing the solution.
- 2Understanding how to handle edge cases, especially related to integer overflow, is crucial for robust solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.