Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Runtime: 8ms
1 class Solution { 2 public: 3 int divide(int dividend, int divisor) { 4 if(divisor == 0) return INT_MAX; 5 6 long long newDividend = dividend; 7 if(newDividend < 0) newDividend = -newDividend; 8 long long newDivisor = divisor; 9 if(newDivisor < 0) newDivisor = -newDivisor; 10 11 bool negative = ((dividend < 0 && divisor > 0 )|| (dividend > 0 && divisor < 0)); 12 long long divis = newDivisor; 13 14 long long result = 0; 15 while(divis <= newDividend){ 16 long long times = 1; 17 18 while(divis <= newDividend){ 19 divis <<= 1; 20 times <<= 1; 21 } 22 newDividend -= (divis >> 1); 23 divis = newDivisor; 24 result += (times >> 1); 25 } 26 if(result > INT_MAX){ 27 if(negative && result + INT_MIN <= 0) 28 result = result; 29 else 30 result = INT_MAX; 31 } 32 return negative ? -result : result; 33 } 34 };