LeetCode 29: Divide Two Integers Solution
Master LeetCode problem 29 (Divide Two Integers), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
29. Divide Two Integers
Problem 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:
- Handle edge cases: Check if either dividend or divisor is equal to 0.
- Determine the sign of the result based on whether both dividend and divisor have the same sign or not.
- Convert both dividend and divisor to positive numbers to simplify the calculation.
- Count the number of times you can subtract the divisor from the dividend without making the dividend negative. This count will be the quotient.
- Ensure the result is within the 32-bit signed integer range.
- Return the result with the correct sign.
Time Complexity: O(log(dividend/divisor)) Space Complexity: O(1)
:
Solution Code
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;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 29 (Divide Two Integers)?
This page provides optimized solutions for LeetCode problem 29 (Divide Two Integers) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 29 (Divide Two Integers)?
The time complexity for LeetCode 29 (Divide Two Integers) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 29 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 29 in Java, C++, or Python.