In this problem, we are asked to divide two integers. However, we are not allowed to use division, multiplication and mod operations. So, what else can be use? Well, bit manipulations.
Let‘s look at an example and see how bit manipulation might help.
Suppose we want to divide 15 by 3, so 15 is dividend and 3 is divisor. Well, division simply requires us to find how many times can we subtract the divisor from the the dividend without making the latter negative. Let‘s get started. We subtract 3 from 15 and we get 12, which is positive, so let‘s try to subtract more. Well, we shift 3 to the left by 1 bit and we get 6. Subtracting 6 from 15 still gives a positive answer. Well, we shift again and get 12. We subtract 12 from 15 and the answer is still positive. We shift again, obtaining 24 and we know we can at most subtract 12. Well, since 12 is obtained by shifting 3 to left twice, we know it is 4 times of 3. How do we obtain this 4? Well, we start from 1 and shift it to left twice, at the same time. We add 4 to an answer. In fact, the above process is like 15 = 3 * 4 + 3. We now get part of the quotient (4), with a remainder 3.
Then we repeat the above process again. We subtract divisor 3 from the remaining dividend 3 and obtain 0. We know we are done. No shift happens, so we simply add 1 << 0 to the answer.
Now we have had the full algorithm to perform division.
According to the problem statement, we need to handle some exceptions, such as flow.
Well, two cases may cause overflow:
- divisor = 0;
- dividend = INT_MIN and divisor = -1 (because abs(INT_MIN) = abs(INT_MAX) + 1).
Of course, we also need to take the sign into account, which is relatively easy.
Putting things together, we have the following code.
1 int divide(int dividend, int divisor) { 2 if (!divisor || (dividend == INT_MIN && divisor == -1)) 3 return INT_MAX; 4 long long dvd = labs(dividend); 5 long long dvs = labs(divisor); 6 int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1; 7 int res = 0; 8 while (dvd >= dvs) { 9 long long tmp = dvs, multiple = 1; 10 while (dvd >= (tmp << 1)) { 11 tmp <<= 1; 12 multiple <<= 1; 13 } 14 dvd -= tmp; 15 res += multiple; 16 } 17 return sign * res; 18 }