# 29.divide two integers

**<font color=red>难度Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/divide-two-integers/
> 内容描述

```
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3
Example 2:

Input: dividend = 7, divisor = -3
Output: -2
Note:

Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [?231,  231 ? 1]. For the purpose of this problem, assume that your function returns 231 ? 1 when the division result overflows.

```
> 思路
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

这里如果直接用暴力的方法肯定超时，这里我牺牲了空间换时间，不过由于 int 最大为2^31 - 1 所以数组的大小也是固定的。这里我们用倍增法，先定义一个res = 0，每次都计算 res += divisor * 2^n 直到大于dividend ，接着再从 res = divisor * 2^(n-1)开始，直到某个res + divisor > dividend


```cpp
class Solution {
public:
    int divide(int dividend, int divisor) {
        if(!dividend)
        return 0;
        long long arr[33];
        arr[0] = 1;
        for(int i = 1;i < 33;++i)
            arr[i] = arr[i - 1] * 2;
        long long temp1 = dividend,temp2 = divisor;
        if(temp1 < 0)
            temp1 *= -1;
        if(temp2 < 0)
            temp2 *= -1;
        long long res,pre = 0,ret = 0;
        int count1 = 0;
        while(1)
        {
            res = pre + arr[count1] * temp2;
            if(res > temp1)
            {
                if(!count1)
                    break;
                pre = pre + arr[count1 - 1] * temp2;
                ret += arr[count1 - 1];
                count1 = 0;
            }
            else
                count1++;
        }
        if(dividend < 0)
            ret *= -1;
        if(divisor < 0)
            ret *= -1;
        if(ret == 2147483648)
            return ret - 1;
        return ret;
    }
};
```