Problem 29

Abstract / Summary

Given two integers divide the first by the second without using multiplication division or modulus operators and return the quotient.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
20 lines | 549 bytes | submitted August 28, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 20% (6+ million submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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, the min function caps the positive result, and the max function 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 > 0 fails immediately, leaving c at 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 than a for all shift values. Consequently, the inner if never triggers, c remains 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 than b << shift for 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 << shift replaces costly multiplication or repeated addition. Bit shifting is a constant-time operation on modern processors, making each iteration lightweight.

  • Early subtraction - By testing a >= sub before 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 7 | μ = 6.50 | σ = 1.64

Complexity Analysis

Time: constant
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
48 links | 32 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Leetcode 29 - Bit Manipulation | Divide Two Integers'
Nideesh Terapalli 10 mins
Leetcode 29 - Bit Manipulation | Divide Two Integers
YouTube video 'Divide Two Integers Python Solution - LeetCode #29'
Professor Oakes 10 mins
Divide Two Integers Python Solution - LeetCode #29
YouTube video '[English] LeetCode 29. Divide Two Integers'
happygirlzt 10 mins
[English] LeetCode 29. Divide Two Integers
YouTube video 'Divide Two Integers | Leetcode 29 | Live coding session'
Coding Decoded 10 mins
Divide Two Integers | Leetcode 29 | Live coding session
YouTube video 'Divide Two Integer (LeetCode 29) | Without the use of multiply and division operator | Bitwise'
Nikhil Lohia 18 mins
Divide Two Integer (LeetCode 29) | Without the use of multiply and division operator | Bitwise
YouTube video 'LeetCode: 29. Divide Two Integers (Visualized)'
Code With Zi 21 mins
LeetCode: 29. Divide Two Integers (Visualized)
YouTube video 'Divide Two Integers - Facebook Interview Question - Leetcode 29 - Python'
CheatCode Ninja 6 mins
Divide Two Integers - Facebook Interview Question - Leetcode 29 - Python
YouTube video 'Divide two integers | Leetcode problem #29 | Explanation(tamil) and code in python'
Code with Vasanth 4 mins
Divide two integers | Leetcode problem #29 | Explanation(tamil) and code in python
YouTube video 'Amazon Coding Interview Question | Leetcode 29 | Divide Two Integers'
WorkWithGoogler 14 mins
Amazon Coding Interview Question | Leetcode 29 | Divide Two Integers
YouTube video 'Daily Leetcode #790: May 30, 2022 - 29. Divide Two Integers'
Programming Live with Larry 23 mins
Daily Leetcode #790: May 30, 2022 - 29. Divide Two Integers
YouTube video 'Leetcode Question 29 "Divide Two Integers" in Javascript'
Ghumman Tech 7 mins
Leetcode Question 29 "Divide Two Integers" in Javascript
YouTube video 'Daily Leetcode #333: Feb 27, 2021 - 29. Divide Two Integers'
Programming Live with Larry 20 mins
Daily Leetcode #333: Feb 27, 2021 - 29. Divide Two Integers
YouTube video 'Day 346: LeetCode Problem 29. Divide Two Integers - Swift'
iOSxBank 12 mins
Day 346: LeetCode Problem 29. Divide Two Integers - Swift
YouTube video '29. Divide Two Integers | Approach 3: Adding Powers of Two| O(LogN) | Leetcode | Medium'
Software Interviews Prep 24 mins
29. Divide Two Integers | Approach 3: Adding Powers of Two| O(LogN) | Leetcode | Medium
YouTube video '29. Divide Two Integers |  Approach 1: Repeated Subtraction | O(N)| Leetcode | Medium | Javascript'
Software Interviews Prep 12 mins
29. Divide Two Integers | Approach 1: Repeated Subtraction | O(N)| Leetcode | Medium | Javascript
YouTube video 'LeetCode: 29. Divide Two Integers(Golang & Java)'
Nandeshwar Sah 16 mins
LeetCode: 29. Divide Two Integers(Golang & Java)
YouTube video 'No Sound Leetcode 29: Divide two integers'
ExtremeProgrammer 4 mins
No Sound Leetcode 29: Divide two integers
17 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 1 medium
3 solutions   August 28, 2023

Fun Facts

This medium problem has the lowest acceptance rate of just 20%.

1 fun fact

Extra

There are a few extra pages giving you some insights into my setup:
  • 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