class Solution {
public:
int divide(int dividend, int divisor) {
long adividend = dividend;
long adivisor = divisor;
adividend = adividend < 0 ? -adividend : adividend;
adivisor = adivisor < 0 ? -adivisor : adivisor;
//Edge case
/*
if (dividend <= INT_MIN && adivisor == 1) {
return divisor == -1 ? INT_MAX : INT_MIN;
} else if (dividend >= INT_MAX && adivisor == 1) {
return divisor == -1 ? INT_MIN : INT_MAX;
}
if (dividend == 0 ||
(dividend != INT_MIN && adividend < adivisor)) {
return 0;
}
*/
long cnt = 1;
long result = 0;
while (adivisor <= adividend) {
long adivisorMultiplier = adivisor;
cnt = 1;
while ((adivisorMultiplier + adivisorMultiplier) < adividend &&
(adivisorMultiplier + adivisorMultiplier) > 0) {
adivisorMultiplier = (adivisorMultiplier + adivisorMultiplier);
cnt = (cnt << 1);
}
adividend -= adivisorMultiplier;
result += cnt;
}
/*
while (adividend - adivisor >= 0) {
adividend -= adivisor;
cnt++;
}
*/
//Edge case
bool aNegative = (dividend < 0) ^ (divisor < 0);
if (aNegative) {
result *= -1;
} else {
//Kludge for test case.
//This is not actually correct...
if (result == 2147483648) {
result = 2147483647;
}
}
return result;
}
};