In order to solve this problem, it is good to know some basics first.
Suppose, dividend is a1, divisor is a0.
a1 = a0 * (2^k) + a0 *(2^(k-1)) + a0*(2^(k-2)) + ... a0 *(2 ^ 1)+ a0*(2^0) +a2...(a2 < a0) if it is dividable, the result is k + k-1 +...0
Several examples can better illustrate this problem.
(9, 4) 9 = (8, 4) + (1, 4), (8, 4) == 2, (1, 4) == 0, Thus, (9, 4) = 2
(15, 4) = (8, 4) + (4, 4) + (3, 4) ---> 3
To find the (8, 4), we just need to shift 4 for k left steps, until it is larger than the dividend. k is the result.
#include <iostream> #include <climits> using namespace std; /* Divide two integers without using multiplication, division and mod operator. If it is overflow, return MAX_INT. */ int divide(int dividend, int divisor) { bool negativeFlag = false; if(dividend < 0 && divisor >= 0) negativeFlag = true; if(dividend >= 0 && divisor < 0) negativeFlag = true; int newDividend = abs(dividend); int newDivisor = abs(divisor); if(newDivisor == 1) return negativeFlag ? -1* newDividend : newDividend; if(newDivisor == 0) return INT_MAX; if(newDivisor > newDividend || newDividend == 0) return 0; int count = 0; while(newDividend > 0) { int tmp = newDivisor; int k = 0; while(tmp <= newDividend) { k++; tmp = tmp << 1; } count += k; newDividend = newDividend - (tmp >> 1); } return negativeFlag ? -1 * count : count; } int main(void) { cout << "9 divide 3" << endl; cout << "res: " << divide(9, 3) << endl; cout << "9 divide 4" << endl; cout << "res: " << divide(9, 4) << endl; cout << "9 divide -3" << endl; cout << "res: " << divide(9, -3) << endl; cout << "9 divide 10" << endl; cout << "res: " << divide(9, 10) << endl; cout << "9 divide 0" << endl; cout << "res: " << divide(9, 0) << endl; cout << "9 divide 1" << endl; cout << "res: " << divide(9, 1) << endl; }