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;
}
}
位运算除法
本文介绍了一种不使用乘法、除法和取模运算符来实现整数除法的方法。仅利用加法、减法及位操作实现了算法,并考虑了溢出情况。通过不断左移除数直至其大于被除数,进行位操作计算商。
2866

被折叠的 条评论
为什么被折叠?



