Python 0029.py
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
a = abs(dividend)
b = abs(divisor)
c = 0
shift = 33
while a > 0 and shift >= 0:
sub = b << shift
if a >= sub:
a -= sub
c += 1 << shift
shift -= 1
if dividend >= 0 and divisor >= 0:
return min(c, +2147483647)
if dividend < 0 and divisor < 0:
return min(c, +2147483647)
return max(-c, -2147483648)
Difficulty
and has an acceptance rate of about 20% (6+ million submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the integer quotient of two signed 32-bit numbers without using the division operator. It follows a classic binary long-division approach: repeatedly subtracting the largest possible multiple of the divisor from the dividend, where each multiple is expressed as a left-shifted version of the divisor. The algorithm works entirely with integer arithmetic and respects the overflow limits defined for 32-bit signed integers.
Core Logic
The method begins by converting both operands to their absolute values, storing them in a and b. This normalization allows the division loop to operate on non-negative numbers only, simplifying the comparison and subtraction steps.
a = abs(dividend)
b = abs(divisor)
A counter c is initialized to accumulate the resulting quotient, and a variable shift is set to 33. The value 33 is chosen because shifting a 32-bit integer left by 33 positions guarantees that the shifted divisor will exceed any possible dividend, ensuring the loop starts with a safe upper bound.
c = 0
shift = 33
The main loop runs while there is still a remainder (a > 0) and the shift index remains non-negative. Inside the loop, the divisor is left-shifted by the current shift amount, producing a candidate multiple sub. If the current remainder a is at least as large as sub, the algorithm subtracts sub from a and adds the corresponding power of two (1 << shift) to the quotient accumulator c. After each iteration, shift is decremented, moving the algorithm to consider progressively smaller multiples.
while a > 0 and shift >= 0:
sub = b << shift
if a >= sub:
a -= sub
c += 1 << shift
shift -= 1
When the loop finishes, c holds the magnitude of the quotient. The final step determines the correct sign based on the original signs of dividend and divisor. If both operands share the same sign, the result is positive; otherwise, it is negative. The code also clamps the result to the 32-bit signed integer range, returning 2147483647 for positive overflow and -2147483648 for negative overflow.
if dividend >= 0 and divisor >= 0:
return min(c, +2147483647)
if dividend < 0 and divisor < 0:
return min(c, +2147483647)
return max(-c, -2147483648)
Edge Cases Handled
The implementation explicitly addresses several boundary conditions:
-
Sign combinations - By checking the sign of both inputs, the code correctly produces a positive quotient when the signs match and a negative quotient when they differ. This covers the four possible sign scenarios without requiring additional arithmetic.
-
Overflow protection - The result is bounded by the maximum and minimum values representable in a 32-bit signed integer. When the computed magnitude exceeds
2147483647, theminfunction caps the positive result, and themaxfunction caps the negative result at-2147483648. This ensures compliance with typical language specifications for integer division overflow. -
Zero dividend - If the dividend is zero, the loop condition
a > 0fails immediately, leavingcat zero. The subsequent sign logic returns zero, which matches the mathematical definition of zero divided by any non-zero divisor. -
Large divisor relative to dividend - When the absolute divisor is larger than the absolute dividend, the first shifted multiple (
b << shift) will be greater thanafor all shift values. Consequently, the innerifnever triggers,cremains zero, and the method returns zero after sign handling. This correctly reflects the integer division rule that a smaller absolute dividend yields a quotient of zero. -
Maximum shift range - Starting the shift at 33 guarantees that even the largest possible 32-bit dividend (
2^31-1) will be smaller thanb << shiftfor any non-zero divisor, preventing an out-of-range shift operation and ensuring the loop begins with a safe comparison.
Performance Optimizations
The algorithm leverages bitwise operations to achieve efficient division:
-
Left-shift multiplication - Multiplying the divisor by powers of two using
b << shiftreplaces costly multiplication or repeated addition. Bit shifting is a constant-time operation on modern processors, making each iteration lightweight. -
Early subtraction - By testing
a >= subbefore performing subtraction, the code avoids unnecessary updates to the remainder and quotient. This conditional check ensures that only the largest feasible multiple is subtracted at each step, reducing the total number of iterations. -
Fixed iteration count - The loop iterates at most 34 times (from shift 33 down to 0). This deterministic bound eliminates dependence on the magnitude of the inputs, providing predictable execution time regardless of the specific values of dividend and divisor.
-
Avoidance of division operator - The entire computation is performed with integer arithmetic and bitwise shifts, which are typically faster than invoking a hardware division instruction, especially in environments where division is expensive or unavailable.
-
Minimal auxiliary storage - Only a handful of integer variables (
a,b,c,shift,sub) are used, keeping the memory footprint low and avoiding cache pressure.
Through these techniques, the solution delivers a fast, low-overhead integer division routine that conforms to the constraints of 32-bit signed arithmetic.
ELI5 - Simplified Explanation
Imagine sharing a giant pile of cookies with friends. This code acts like a very smart cookie counter that figures out how many times one number can fit into another without using a simple division button.
First, it looks at the two numbers and ignores any negative signs, just like pretending all your cookies are positive and happy. It treats the cupboard as a place to keep track of how many groups have been distributed.
Then, there is a clever trick using a slide. Instead of taking away little bits one by one, it looks at the divisor and slides it over to make it much bigger. It tries to subtract this huge chunk from the total number of cookies as many times as possible. Every time those big chunks fit, the counter grows by that same amount. After checking every possible size, starting from a really big shift all the way down to one, the work is done.
Finally, the code checks the original signs of the numbers. If the first number and the second number were both positive or both negative, the answer stays positive. If they were different, it turns the answer negative. It also makes sure the result stays within a safe playground size so that the numbers do not get too big or too small to handle.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | PHP | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| lzl124631x | C++ | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, PHP, Python, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| halfrost | Go | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| lzl124631x | C++ | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
Fun Facts
This medium problem has the lowest acceptance rate of just 20%.
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality