Divide two integers without using multiplication, division and mod operator.
Division is not performed by multiplication, division, or modulo operation. That is to say, only addition and subtraction and bitwise operations can be used. The natural idea is to subtract the divisor each time and determine how many times the divisor is subtracted. This is the result, this will time out when the divisor is large and the divisor is small. Therefore, based on this, we can increase the number of divisor each time and then reduce it until the divisor is greater than the divisor, and then divide the divisor by 2 each time, perform subtraction until the divisor is equal to zero, which can accelerate. In this process, doubling and dividing by 2 can be achieved by bitwise operations.
The Code is as follows:
1 public int divide(int dividend, int divisor) { 2 int count = 0; 3 long a = Math.abs((long)dividend); 4 long b = Math.abs((long)divisor); 5 boolean isNegative = (dividend ^ divisor) >= 0; 6 long i = 1; 7 for (; a >= b; i<<=1, b <<= 1) { 8 a -= b; 9 count += i;10 }11 for (; i > 0; i>>=1, b >>= 1) {12 if (a >= b) {13 a -= b;14 count += i;15 }16 }17 return isNegative ? count : -count;18 }
ACSS 520 Ms