leetcode 29两数相除-LMLPHP

我理解本题是考察基于加减实现除法,代码如下:

class Solution {
public:
//只用加减号实现除法,
//不用加减号实现除法;
int divide(int dividend, int divisor) {
//
if(dividend==INT_MIN&&divisor==-){
return INT_MAX;
}
long dvd=labs(dividend);long dvs=labs(divisor);long ans=;
int sign=dividend^divisor;
for(int i=;i>=;i--){
if((dvd>>i)>=dvs){
dvd-=dvs<<i;
ans+=<<i;
}
}
if(sign<)
ans=-ans;
return ans;
} };

如果单纯基于位运算呢?加减也依靠位运算如何避免溢出?

以下为不使用“+ - * / ”四个符号完成计算:

class Solution {
public:
//只用加减号实现除法,
//不用+ - * / 实现除法;
const int minus_one=substract(,);
int divide(int dividend, int divisor) {
if (dividend == INT_MIN && divisor == minus_one) {
return INT_MAX;
}
long dvd = long(dividend<?add(~dividend,):dividend), dvs = long(divisor<?add(~divisor,):divisor), ans = ;
if(dividend==INT_MIN) dvd=;
if(divisor==INT_MIN) dvs=;
/**test for some cases
cout<<dvd<<","<<dvs<<endl;
cout<<labs(dvd)<<","<<labs(dvs)<<endl;
cout<<add(~divisor,); **/ int sign = dividend > ^ divisor > ? minus_one : ;
while (dvd >= dvs) {
long temp = dvs, m = ;
while (temp << <= dvd) {
temp <<= ;
m <<= ;
}
dvd =substract(dvd,temp);
ans =add(ans,m);
}
return sign>?ans:substract(,ans);
}
int add(int a,int b){
long long carry=b;
while(b!=){
carry=a&b;
a=a^b;
b=(carry&0xffffffff)<<;//避免负数左移溢出
}
return a;
}
int substract(int a,int b){
int c=add(~b,);
int res=add(a,c);
return res;
}
};
05-11 19:23