Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Analysis
We can use subtract to solve this solution.But it's too slow when the divisor is particularly small comparing to dividend.The better way is to use shift.
将diviend和divisor转换成long型并取绝对值,防止MIN_VALUE取绝对值后仍然返回负值
Step 1: 当dividend大于divisor时,左移divisor直到divisor大于dividend,记下divisor左移的位数n,dividend减去divisor<<n,结果值加上1<<n((a+b)/c = a/c + b/c)
Step 2:如果更新的divisend仍然大于divisor,则继续执行Step1
/**
* Divide two integers without using multiplication, division and mod operator.
*
* If it is overflow, return MAX_INT.
*
* @author Sam
*
*/
public class DivideTwoInteger {
public static void main(String[] args) {
System.out.println(divide(-1010369383, -2147483648));
}
public static int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
//convert the integer to long type for eliminate the strange performance of the Integer.MIN_VALUE
long dd = Math.abs((long) dividend);
long dr = Math.abs((long) divisor);
int n, res = 0;
while (dd >= dr) {
n = 0;
//shift divisor
while (dd >= dr << ++n);
res += 1 << (n - 1);
dd -= dr << (n - 1);
}
return (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) ? -res : res;
}
}
Complexity
O(log n)