# 两数相除

<p>给定两个整数，被除数&nbsp;<code>dividend</code>&nbsp;和除数&nbsp;<code>divisor</code>。将两数相除，要求不使用乘法、除法和 mod 运算符。</p><p>返回被除数&nbsp;<code>dividend</code>&nbsp;除以除数&nbsp;<code>divisor</code>&nbsp;得到的商。</p><p>整数除法的结果应当截去（<code>truncate</code>）其小数部分，例如：<code>truncate(8.345) = 8</code> 以及 <code>truncate(-2.7335) = -2</code></p><p>&nbsp;</p><p><strong>示例&nbsp;1:</strong></p><pre><strong>输入:</strong> dividend = 10, divisor = 3<strong><br />输出:</strong> 3<strong><br />解释: </strong>10/3 = truncate(3.33333..) = truncate(3) = 3</pre><p><strong>示例&nbsp;2:</strong></p><pre><strong>输入:</strong> dividend = 7, divisor = -3<strong><br />输出:</strong> -2<strong><br />解释:</strong> 7/-3 = truncate(-2.33333..) = -2</pre><p>&nbsp;</p><p><strong>提示：</strong></p><ul>	<li>被除数和除数均为 32 位有符号整数。</li>	<li>除数不为&nbsp;0。</li>	<li>假设我们的环境只能存储 32 位有符号整数，其数值范围是 [&minus;2<sup>31</sup>,&nbsp; 2<sup>31&nbsp;</sup>&minus; 1]。本题中，如果除法结果溢出，则返回 2<sup>31&nbsp;</sup>&minus; 1。</li></ul>

以下程序实现了这一功能，请你填补空白处内容：

```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	int divide(int dividend, int divisor)
	{
		int signal = 1;
		unsigned int dvd = dividend;
		if (dividend < 0)
		{
			signal *= -1;
			dvd = ~dvd + 1;
		}
		unsigned int dvs = divisor;
		if (divisor < 0)
		{
			signal *= -1;
			dvs = ~dvs + 1;
		}
		int shift = 0;
		while (dvd > dvs << shift)
		{
			shift++;
		}
		unsigned int res = 0;
		while (dvd >= dvs)
		{
			________________;
		}
		if (signal == 1 && res >= INT_MAX)
		{
			return INT_MAX;
		}
		else
		{
			return res * signal;
		}
	}
};
```

## template

```cpp
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	int divide(int dividend, int divisor)
	{
		int signal = 1;
		unsigned int dvd = dividend;
		if (dividend < 0)
		{
			signal *= -1;
			dvd = ~dvd + 1;
		}
		unsigned int dvs = divisor;
		if (divisor < 0)
		{
			signal *= -1;
			dvs = ~dvs + 1;
		}
		int shift = 0;
		while (dvd > dvs << shift)
		{
			shift++;
		}
		unsigned int res = 0;
		while (dvd >= dvs)
		{
			while (dvd < dvs << shift)
			{
				shift--;
			}
			res |= (unsigned int)1 << shift;
			dvd -= dvs << shift;
		}
		if (signal == 1 && res >= INT_MAX)
		{
			return INT_MAX;
		}
		else
		{
			return res * signal;
		}
	}
};
```

## 答案

```cpp
while (dvd < dvs << shift)
{
	shift--;
}
res |= (unsigned int)1 << shift;
dvd -= dvs << shift;
```

## 选项

### A

```cpp
while (dvd < dvs << shift)
{
	shift--;
}
res &= (unsigned int)1 << shift;
dvd -= dvs << shift;
```

### B

```cpp
while (dvd < dvs << shift)
{
	shift--;
}
res &= (unsigned int)1 >> shift;
dvd -= dvs << shift;
```

### C

```cpp
while (dvd < dvs << shift)
{
	shift--;
}
res |= (unsigned int)1 >> shift;
dvd -= dvs << shift;
```