Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 29: Divide Two Integers

MathBit Manipulation

LeetCode 29 Solution Explanation

Explanation:

To solve this problem without using multiplication, division, and mod operators, we can simulate the process of long division. We repeatedly subtract the divisor from the dividend until the dividend becomes less than the divisor. The number of times we can subtract the divisor without making the dividend negative will be the quotient. We need to handle the edge cases where the dividend or divisor is negative and also take care of overflow scenarios.

Algorithmic Steps:

  1. Handle edge cases: Check if either dividend or divisor is equal to 0.
  2. Determine the sign of the result based on whether both dividend and divisor have the same sign or not.
  3. Convert both dividend and divisor to positive numbers to simplify the calculation.
  4. Count the number of times you can subtract the divisor from the dividend without making the dividend negative. This count will be the quotient.
  5. Ensure the result is within the 32-bit signed integer range.
  6. Return the result with the correct sign.

Time Complexity: O(log(dividend/divisor)) Space Complexity: O(1)

:

LeetCode 29 Solutions in Java, C++, Python

class Solution {
    public int divide(int dividend, int divisor) {
        if (dividend == 0) return 0;
        if (divisor == 1) return dividend;
        if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;

        boolean isNegative = (dividend < 0) ^ (divisor < 0);
        long dvd = Math.abs((long) dividend);
        long dvs = Math.abs((long) divisor);
        long result = 0;

        while (dvd >= dvs) {
            long temp = dvs, multiple = 1;
            while (dvd >= (temp << 1)) {
                temp <<= 1;
                multiple <<= 1;
            }
            dvd -= temp;
            result += multiple;
        }

        return isNegative ? (int) -result : (int) result;
    }
}

Interactive Code Editor for LeetCode 29

Improve Your LeetCode 29 Solution

Use the editor below to refine the provided solution for LeetCode 29. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems