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)
3. Time & Space Complexity
倍增法:时间复杂度O(log(divisor)), 空间复杂度O(1)
Last updated
Was this helpful?