https://leetcode.com/problems/divide-two-integers/submissions/
Given two integers
dividend
anddivisor
, divide two integers without using multiplication, division and mod operator.Return the quotient after dividing
dividend
bydivisor
.The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3 Output: 3Example 2:
Input: dividend = 7, divisor = -3 Output: -2Note:
- 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.
原本想像之前模拟加法一样从cpu运算层面出发进行,但是cpu内部的除法本身就很复杂(系统结构白学)。
其实不用这么复杂的考虑,模拟出发最直接的方法自然就是一个一个从被除数中减去除数,但是效率太低,最好能够批量消除,又不能用乘法,最直观的方法就是移位。
从另一个角度看就相当于找到最后的除法结果的二进制表示的每一位比特。
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend == INT_MIN && divisor == -1) return INT_MAX;
long long result = 0;
long long tem_num, tem_cnt;
bool neg = false;
long long tr_dividend = dividend;
long long tr_divisor = divisor;
if(tr_dividend < 0){
tr_dividend = -tr_dividend;
neg = !neg;
}
if(tr_divisor < 0){
tr_divisor = -tr_divisor;
neg = !neg;
}
while(tr_dividend >= tr_divisor){
tem_num = tr_divisor;
tem_cnt = 1;
while(tr_dividend >= tem_num){
tem_num <<= 1;
tem_cnt <<= 1;
}
tr_dividend -= (tem_num >> 1);
result += (tem_cnt >> 1);
}
if(neg) result = -result;
return result;
}
};