29. Divide Two Integers
Posted ArgenBarbie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了29. Divide Two Integers相关的知识,希望对你有一定的参考价值。
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; }
以上是关于29. Divide Two Integers的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 29. Divide Two Integers