不用“加减乘除”实现“加减乘除运算”
程序员文章站
2024-02-27 17:59:57
...
换了n种方法,终于是跑通了一个不超时的,记录一下
class Solution {
public int divide(int dividend, int divisor) {
boolean isMinus = ((dividend<0 && divisor >0) || (dividend>0 && divisor <0)); //异号为true,同号为false
if( Integer.MIN_VALUE == dividend){
if(1 == divisor)
return dividend;
else if(2 == divisor)
return dividend >> 1;
else if(Integer.MIN_VALUE == divisor)
return 1;
}else if(Integer.MIN_VALUE == divisor)
return 0;
dividend = Math.abs(dividend);
//abs(Integer.MIN_VALUE) = Integer.MIN_VALUE
dividend = dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : dividend;
divisor = Math.abs(divisor);
int sub = divisor; //接下来要减的数,每次翻倍
int c = 1;//减的数翻倍,要加到结果上的数也得翻倍
int ret = 0;
while(dividend >= divisor){
if(dividend >= sub){
dividend=minus(dividend, sub);
ret=add(ret,c);
sub=(sub<<1);
c=(c<<1);
}else{
sub=(sub>>1);
c=(c>>1);
}
}
if(isMinus)
ret=add(~ret,1);
return ret;
}
public int multi(int a, int b){
if(b == 0)
return 0;
else if(1 == b)
return a;
else if(-1 == b)
return 0-a;
if(a < 0 && b < 0){
return multi(add(~a, 1), add(~b, 1));
}else if(a < 0 && b > 0){
return 0 - multi(add(~a, 1), b);
}else if(a > 0 && b < 0){
return 0 - multi(a, add(~b, 1));
}else{
for(int i = 1; i < 32; i++){
if( 1 << i > b){ //找到比b大的且是2的幂次的最小数
int j = 1 << (i-1); //比b小的且是2的幂次的最大数
return add(a << (i-1) , multi(a, b-j));
}
}
}
return 0;
}
public int minus(int a, int b){
return add(a, add(~b, 1));
}
public int add(int a, int b){
int aa = a;
int bb = b; //进位
while(bb != 0){
aa = a ^ b;
bb = (a & b) << 1;
b = bb;
a = aa;
}
return aa;
}
}
上一篇: Mysql数据库命令大全
下一篇: 连接Redis