Divide two integers without using multiplication, division and mod operator.
Only plus, minus, and bit manipulation is allowed to solve this question. Left shifting a integer by a bit is actually doubling that integer. So keep left shifting the divisor until the result is larger than the dividend. Calculate the dividend minus the last result after shifting the divisor, and use the minus result to continue the bit manipulation, until it's smaller than the divisor.
Note the possibility of overflow when calculating the absolute value of the dividend and the divisor.
public class Solution {
public int divide(int dividend, int divisor) {
boolean diffSign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
long a = Math.abs((long) dividend);
long b = Math.abs((long) divisor);
int res = 0;
while (a >= b) {
int shift = 0;
while ((b << shift) <= a) {
shift++;
}
res += 1 << (shift - 1);
a -= b << (shift - 1);
}
return diffSign ? -res : res;
}
}