Divide Two Integers
问题描述:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
知识补充:
移位运算
a<<1;//移位时,移出的位数全部丢弃,移出的空位补入的数与左移还是右移花接木有关。如果是左移,则规定补入的数全部是0;如果是右移,还与被移位的数据是否带符号有关。若是不带符号数,则补入的数全部为0;若是带符号数,则补入的数全部等于原数的最左端位上的原数(即原符号位)
//类似于乘除法,左移一位相当于乘以2.两位乘以4
参考答案:
class Solution {
public:
int divide(int& n_, int& d_) {
long n = abs((long)n_), d = abs((long)d_), res = 0;
while(n>=d){
long a = d, count = 1;
while((a<<1)<n){a<<=1; count<<=1;}
res += count;
n -= a;
}
if(n_>0 ^ d_>0) return -res;
return min((long)INT_MAX, max((long)INT_MIN, res));
}
};