Divide two integers without using multiplication, division and mod operator.
1 class Solution { 2 private: 3 long long f[100]; 4 public: 5 int bsearch(long long a[], int left, int right, long long key) 6 { 7 if (left > right) 8 return -1; 9 10 int mid = left + (right - left) / 2; 11 if (a[mid] == key) 12 return mid; 13 else if (a[mid] < key) 14 { 15 int pos = bsearch(a, mid + 1, right, key); 16 return pos == -1 ? mid : pos; 17 } 18 else 19 { 20 return bsearch(a, left, mid - 1, key); 21 } 22 } 23 24 int divide(int dividend, int divisor) { 25 // Start typing your C/C++ solution below 26 // DO NOT write int main() function 27 int sign = dividend < 0 ? -1 : 1; 28 if (divisor < 0) 29 sign *= -1; 30 31 long long div = dividend; 32 div = abs(div); 33 long long divisorL = divisor; 34 divisorL = abs(divisorL); 35 f[0] = divisorL; 36 int size = 1; 37 while(true) 38 { 39 if (f[size-1] >= div) 40 break; 41 f[size] = f[size-1] + f[size-1]; 42 size++; 43 } 44 45 int num = 0; 46 long long sum = 0; 47 while(div > 0) 48 { 49 int pos = bsearch(f, 0, size - 1, div); 50 if (pos == -1) 51 break; 52 div -= f[pos]; 53 num += (1 << pos); 54 } 55 56 return num * sign; 57 } 58 };