> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/algorithm-practice/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/algorithm-practice/leetcode/binary-search/29-divide-two-integers.md).

# 29 Divide Two Integers

## 29. [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/description/)

## 1. Question

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX\_INT.

## 2. Implementation

**(1) 倍增法**

```java
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

**倍增法:**&#x65F6;间复杂度O(log(divisor)), 空间复杂度O(1)
