标签:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
(1) log
int divide(int dividend, int divisor) { if(dividend == 0) return 0; if(divisor == 0) return INT_MAX; double t1 = log(fabs(dividend)), t2 = log(fabs(divisor)); long long ans = (double)exp(t1-t2); if((dividend > 0) ^ (divisor > 0)) ans = -ans; if(ans > INT_MAX) return INT_MAX; return ans; }
注意:
abs(-2147483648) = -2147483648, fabs(-2147483648) = 2147483648
(2) Binary Index tree idea inspired solution, as we can decompose any result number to sum of the power of 2.
int divide(int dividend, int divisor) { long long result = 0; long long m = abs((long long)dividend); long long n = abs((long long)divisor); while (m >= n) { long long s = n, power = 1; while ((s << 1) <= m) { s <<= 1; power <<= 1; } result += power; m -= s; } if ((dividend>0) ^ (divisor>0)) result = -result; return result>INT_MAX ? INT_MAX : result; }
标签:
原文地址:http://www.cnblogs.com/argenbarbie/p/5243847.html