Divide two integers without using multiplication, division and mod operator.
There are two major problems:
1. The minimal int is also a test case, so long long is essential.
2. return (1<<(k - 1)) + div(dividend - (divisortmp>>1), divisor); is wrong because of the priority.
The right code is :
class Solution {
public:
long long abs(long long x) {
return x > 0 ? x : (-x);
}
int div (long long dividend, long long divisor) {
if (dividend < divisor)
return 0;
int k = 0;
long long divisortmp = divisor;
for (; dividend >= divisortmp; ++k)
divisortmp <<= 1;
return (1<<(k - 1)) + div(dividend - (divisortmp>>1), divisor);
}
int divide(int dividend, int divisor) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (divisor == 0 || dividend == 0)
return 0;
int sign[3]; // - is 1; + is 0
sign[0] = dividend < 0 ? 1 : 0;
sign[1] = divisor < 0 ? 1 : 0;
sign[2] = sign[0]^sign[1];
long long divisorll = abs((long long)divisor);
long long dividendll = abs((long long)dividend);
int res = div(dividendll, divisorll);
return sign[2] == 0 ? res : -res;
}
};
A better solution:
class Solution {
public:
inline long long abs(long long x) {
//x may be the INT_MIN
return x > 0 ? x : -x;
}
int divide(int dividend, int divisor) {
long long a = abs(dividend), b = abs(divisor);
//int res = 0; // So int is not enough
long long res = 0;
while (a >= b) {
long long c = b;
for (int i = 0; a >= c; ++i, c <<= 1) {
res += 1 << i;
a -= c;
}
}
res = (dividend ^ divisor) >> 31 ? -res : res;
return (int)res;
}
};