# 两数相除

给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。

返回被除数 dividend 除以除数 divisor 得到的商。

整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2

 

示例 1:

输入: dividend = 10, divisor = 3
输出:
3
解释:
10/3 = truncate(3.33333..) = truncate(3) = 3

示例 2:

输入: dividend = 7, divisor = -3
输出:
-2
解释:
7/-3 = truncate(-2.33333..) = -2

 

提示:

## template ```cpp #include 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 ``` ## 选项 ### A ```cpp ``` ### B ```cpp ``` ### C ```cpp ```