Divide two integers without using multiplication, division and mod operator.
Analysis:
Multiplication, division, and modulo operations are not supported. We can use addition, subtraction, and bitwise operations. A simple idea is to subtract the divisor on dividend and know that the remainder is smaller than the divisor. Then, the number of reductions is the result. Here we can use a method similar to binary search to use power-Level Jump to test how many times dividend is divisor, so as to achieve acceleration. There are two ways to perform power-Level Jump. One is dividend first times the divisor, and the other is dividend first minus the maximum multiple of divisor smaller than dividend. Because we can use bitwise shifts to implement the 2power operation, the second method is faster than the first one, especially when dividend and divisor differ a lot.
Leetcode version:
class Solution {public: int divide(int dividend, int divisor) { long long div = (dividend > 0)? dividend:-(long long)dividend; long long dis = (divisor > 0)? divisor: -(long long)divisor; int result = 0; while(div >= dis){ int counter = 0; while(div >= dis<<counter){ counter++; } result += 1<<(counter-1); div -= dis<<(counter-1); } return ((dividend^divisor)>>31)?(-result):result; }};
Timeout version:
class Solution {public: int divide(int dividend, int divisor) { long long div = (dividend > 0)? dividend:-(long long)dividend; long long dis = (divisor > 0)? divisor: -(long long)divisor; int result = 0; while(div >= dis){ long long c = dis; for(int i = 0; div >= c; i++, c<<i){ div -= c; result += 1<<i; } } return ((dividend^divisor)>>31)?(-result):result; }};
Divide two integers