借用位运算符进行加减乘除运算

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010772882/article/details/86225491
思路及部分案例来自:https://blog.csdn.net/itismelzp/article/details/49621741

1 先来掌握一些常用的位运算操作:

 (1)等式:-n = ~(n - 1) = ~n + 1(-n等于其各位取反加1);

 (2)获取整数n的二进制中最后一个1:-n&n 或(~n+1)&n或 ~(n - 1)&n;

 如:n = 010100,则 -n = 101100, n&(n - 1)=000100;

 (3)去掉整数n的二进制中最后一个1:n&(n - 1)。如:n = 010100, n -1 = 010011, n&(n - 1) = 010000。
2 使用位运算符进行加减运算
  
    //add加法实现
    public static int add(int a,int b){
        int noCarry = a^b;      //把不需要进位的先算出来
        int carry   = (a&b)<<1;   //再把需要进位的计算出来
        if (carry!=0){
            return noCarry+carry;
        }else {
            return noCarry;
        }
    }
    //minus减法实现
    public static int minu(int a,int b){
        int min     = a;
        int minuend = ~(b-1);
        int noCarry = min^minuend;
        int carry   = (min&minuend)<<1;
        if (carry!=0){
            return noCarry+carry;
        }else {
            return noCarry;
        }
    }
    //multiply乘法实现
    public static int mul(int a,int b){
        int ans = 0;
        while(b!=0){
            if ((b&1)!=0) ans = add(ans,a);
            a = a<<1;
            b = b>>1;
        }
        return ans;
    }
    //division除法实现  摘自:https://blog.csdn.net/itismelzp/article/details/49621741
    public static double div(int a,int b){
        int ans = 0;
        for (int i =31;i>=0;i--){
            //比较a是否是大于b的(1<<i)次方,避免将a与(b<<i)比较,因为不确定b的(1<<i)次方是否溢出
            if (b<=(a>>i)){
                ans += (1<<i);
                a   -= (b<<i);
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        BitOperation bitOperate = new BitOperation();
        int addRes = bitOperate.add(5,1);
        int subRes = bitOperate.minu(5,-5);
        int mulRes = bitOperate.mul(10,11);

        System.out.println(addRes);
        System.out.println(subRes);
        System.out.println(mulRes);
    }
}

猜你喜欢

转载自blog.csdn.net/u010772882/article/details/86225491
今日推荐