Divide Two Integers
题目描述:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return INT_MAX.
提示中谈到Binary Search,由此可想到解决方案。
solution:
int divide(int dividend, int divisor) { if(divisor == 0) return INT_MAX; if(dividend == INT_MIN && divisor == -1) return INT_MAX; int sign = (dividend > 0 ^ divisor > 0) ? -1 : 1; long long end = abs( (long long)dividend); long long sor = abs( (long long)divisor); long long res = 0; while (end >= sor) { long long tmp = sor; long long power = 1; while ( (tmp << 1) < end) { power <<= 1; tmp <<= 1; } res += power; end -= tmp; } return sign > 0 ? res : -res; }
参考资料:https://leetcode.com/discuss/11358/simple-o-log-n-2-c-solution