//from fish in water, similar to codeganker
int divide(int dividend, int divisor) {
unsigned long dvd = dividend < 0 ? -dividend : dividend;
unsigned long dvs = divisor < 0 ? -divisor : divisor;
if (dvd < dvs) return 0;
int sign = 1;
if (dividend < 0) sign *= -1;
if (divisor <0) sign *= -1;
unsigned long absDivisor = dvs;
int step = 0;
while (dvs < dvd)
{
dvs = dvs << 1;
step++;
}
int result = 0;
while (dvd >= absDivisor)
{
if (dvd >= dvs)
{
dvd -= dvs;
result += 1 << step;
}
dvs = dvs >> 1;
step--;
}
return result * sign;
}
No comments:
Post a Comment