LeetCode 29: Divide Two Integers
Problem Description
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)
:
Solutions
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;
}
}
Related LeetCode Problems
Loading editor...