029-divide-two-integers
Question
https://leetcode.com/problems/divide-two-integers/description/
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Example:
Thought Process
- Convert to Long
- Use two variables to check the accumulative sum and multiplier
- While the dividend is still greater than divisor, we can increase out count
- We can speed up the count by multiplying by 2 using right shift
- Time complexity O(log n)
- Space complexity O(1)
Solution
class Solution {
public int divide(int dividend, int divisor) {
if (divisor == 1) return dividend;
if (divisor == -1) {
return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
}
int ret = 0;
boolean isNegative = (dividend < 0) ^ (divisor < 0) ? true : false;
long ldividend = Math.abs((long) dividend);
long ldivisor = Math.abs((long) divisor);
while (ldividend >= ldivisor) {
long multiple = 1, accum = ldivisor;
while (ldividend >= (accum << 1)) {
accum <<= 1;
multiple <<= 1;
}
ret += multiple;
ldividend -= accum;
}
return isNegative ? -ret : ret;
}
}