（难度Medium）Problem 29. Divide Two Integers（模拟除法）

### 链接

https://leetcode.com/problems/divide-two-integers/

Medium

### 题干

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:

1. Both dividend and divisor will be 32-bit signed integers.

2. The divisor will never be 0.

3. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−$2^{31}-1$, $2^{31}-1$ − 1]. For the purpose of this problem, assume that your function returns $2^{31}-1$ when the division result overflows.

4. 被除数和除数都是32位的int

5. 除数不为0

6. 对于超界的情况，返回$2^{31}-1$

### 解法一： 减法模拟


class Solution {
public:
int divide(int dividend, int divisor) {
// 特判会超界的情况
if (dividend == INT_MIN) {
if (divisor == -1) return INT_MAX;
if (divisor == 1) return INT_MIN;
}
int ret = 0;
// 标记是否同号
bool mark = false;
if (dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0) {
mark = true;
}

      // 全部转成负数
if (dividend > 0)   dividend = -dividend;
if (divisor > 0)    divisor = -divisor;`