Try the following
int divide(int dividend, int divisor) {
int sign = 1;
unsigned long long tmp = abs((long long)dividend);
unsigned long long tmp2 = abs((long long)divisor);
unsigned long c = 1;
int res = 0;
if (dividend<0){sign = -sign;}
if (divisor<0){sign = -sign;}
while (tmp>tmp2){
tmp2 = tmp2<<1;
c = c<<1;
}
while (tmp>=abs((long long)divisor)){
while (tmp>=tmp2){
tmp -= tmp2;
res = res+c;
}
tmp2=tmp2>>1;
c=c>>1;
}
return sign*res;
}
Logic:
1. Keep multiply 2 (<<1) to the divisor, until it is greater than the dividend. Store the times of shift operation.
2. if dividend > divisor, then dividend = dividend - divisor/2(>>1). Until dividend< original divisor. Store the result.
3. Output the result.