29 Divide Two Integers
1. Question
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
2. Implementation
(1) 倍增法
思路: 我们知道每个数都可以用二进制来表示,为了快速得到两个数相除的结果,我们可以利用倍增法的方式得到两个数相除的商的二进制形式。举个例子,87 / 4 = 21 (忽略余数部分), 而 21的二进制形式是10101,所以 87 = 4 * (1 * 2 ^ 4 + 0 * 2 ^ 3 + 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0)
class Solution {
public int divide(int dividend, int divisor) {
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
long res = 0;
while (a >= b) {
long temp = b;
int i = 0;
while (a >= temp) {
a -= temp;
temp <<= 1;
res += 1 << i;
++i;
}
}
if (dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0) {
res = -res;
}
return res > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)res;
}
}
3. Time & Space Complexity
倍增法:时间复杂度O(log(divisor)), 空间复杂度O(1)
Last updated
Was this helpful?