A failure is the case (-2147483648, -2147483648). Here the problem is about the boundary of integer.
For int (32 bits): [-2147483648, 2147483647]
unsigned int [0, 4294967295]
long (32bits) same with the int
long long (64bits)
In line 22: I tried unsigned int as the type of sum, but when I do sum<<1, it became 0, which also happened when I use long here. So finally I tried long long type and it worked.
class Solution {
public:
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) return 0xFFFFFFFF;
if (!dividend) return 0;
unsigned int did = dividend;
unsigned int dis = divisor;
int flag=1;
if (divisor<0) {
dis = divisor*-1;
flag *=-1;
}
if (dividend<0) {
did = dividend*-1;
flag *=-1;
}
int res=0;
while (did>=dis) {
long long sum=dis;
for (int i=0; sum<=did; i++,sum = sum<<1) {
did -=sum;
res += 1<<i;
}
}
return res*flag;
}
};