Divide two integers without using multiplication, division and mod operator.
1 class Solution { 2 public: 3 int divide(int dividend, int divisor) { 4 assert(divisor != 0); 5 int res = 0; 6 bool flag = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0); 7 long long dividend1 = abs((long long)dividend); 8 long long divisor1 = abs((long long)divisor); 9 while(divisor1 <= dividend1) { 10 long long div = divisor1; 11 int quote = 1; 12 while((div << 1) <= dividend1) { 13 div <<= 1; 14 quote <<= 1; 15 } 16 dividend1 -= div; 17 res += quote; 18 } 19 return flag ? res : -res; 20 } 21 };