Divide two integers without using multiplication, division and mod operator.
Use minus and bit operation to simulate division.
For example, we are going to simulate 50 / 4, we can keep doing minus like
until the reminder 2 is smaller than 4, so the result will be 12, for 50 = 4 * 12 + 2. This is a linear complexity which will not be able to pass when dividend is very large (e.g. 2^32 - 1) and divisor (e.g. 1) is very small.
One way we could do is instead of doing linear minus, we do exponential minus by using << operation.
So for any integer a, a << 1 means a * 2, and we do another time it will be a << 1 << 1 -> a * 4. This will be much faster than linear minus.
We can use this technique to do the minus and iteratively we stop when the reminder is smaller than the divisor. This can also be illustrated as following:
a = b * 2^ k1 + b * 2^ k2 + .... m, where m < b
The division result is Sum(2^k1 + 2^k2 ....2^kn)
In addition, there are some tricky data to be careful
Integer overflow when you do the bit operation. I changed to long type to overcome this.
You can read my code here.
https://gist.github.com/zyzyis/3c60af9318ac7807594e
In additional to use bit operation there is another way I found out works. For divide a / b, we can change to logarithm where
log(a/b) = log(a) - log(b)
By using log and minus it actually also works to pass the test. Of course you need to pay attention to float accuracy when writing the program.