Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
class Solution {
public:
int divide(int dividend, int divisor) {
if (divisor == 0 || (dividend == INT_MIN&&divisor == -1))
return INT_MAX;
bool neg = (dividend < 0) ^ (divisor < 0) ? false : true;
long long a = abs((long long)dividend);
long long b = abs((long long)divisor);
long result = 0;
if (b == 1)
return neg ? a : -a;
while (b <= a)
{
long long x = b;
long long shift = 0;
while ((x << 1) <= a)
{
x <<= 1;
shift += 1;
}
result += 1<<shift;
a = a - x;
}
return neg ? result : -result;
}
};