Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
The basic solution is to keep adding divisor until the sum is larger than the dividend. However, this could be very costy for cases such as INT_MAX/1.
So, I use binary bit operation in my solution. The algorithm is very straight forward by following the basic division rule. The only issue is to consider overflow during the process. The tricks here is to rule out evident overflow cases first, then convert int to long. Algorithm takes 8ms to finish all test cases.
No comments:
Post a Comment