java 带按位运算符的两个数字的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15327169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:15:19  来源:igfitidea点击:

Sum of two numbers with bitwise operator

javabit-manipulation

提问by Trying

I am pasting the code to find the sum of two numbers with bitwise operator. Please suggest if it can be optimized. Thanks...

我正在粘贴代码以使用按位运算符查找两个数字的总和。请建议是否可以优化。谢谢...

public static int getSum(int p, int q)
{
int carry=0, result =0;
for(int i=0; i<32; i++)
{
    int n1 = (p & (1<<(i)))>>(i); //find the nth bit of p
    int n2 = (q & (1<<(i)))>>(i); //find the nth bit of q

    int s = n1 ^ n2 ^ carry; //sum of bits
    carry = (carry==0) ? (n1&n2): (n1 | n2); //calculate the carry for next step
    result = result | (s<<(i)); //calculate resultant bit
}

return result;
}

回答by Joop Eggen

Think in entire bits:

整体思考:

public static int getSum(int p, int q)
{
    int result = p ^ q; // + without carry 0+0=0, 0+1=1+0=1, 1+1=0
    int carry = (p & q) << 1; // 1+1=2
    if (carry != 0) {
        return getSum(result, carry);
    }
    return result;
}

This recursion ends, as the carry has consecutively more bits 0 at the right (at most 32 iterations).

此递归结束,因为进位在右侧连续有更多位 0(最多 32 次迭代)。

One can easily write it as a loop with p = result; q = carry;.

人们可以很容易地将它写成一个循环p = result; q = carry;

Another feature in algorithmic exploration is not going too far in differentiating cases. Above you could also take the condition: if ((result & carry) != 0).

算法探索的另一个特点是在区分情况时不会走得太远。上面你也可以采用条件:if ((result & carry) != 0)

回答by Adam Matan

I think that the optimizations should be in the field of readability, rather than performance (which will probably be handled by the compiler).

我认为优化应该在可读性领域,而不是性能(这可能由编译器处理)。

Use for loop instead of while

使用 for 循环而不是 while

The idiom for (int i=0; i<32; i++)is more readable than the while loop if you know the number of iterations in advance.

for (int i=0; i<32; i++)如果您提前知道迭代次数,则该习惯用法比 while 循环更具可读性。

Divide the numbers by two

将数字除以二

Dividing the numbers by two and getting the modulu:

将数字除以二并得到模数:

n1 = p % 2;
p  /= 2;

Is perhaps more readable than:

可能比以下内容更具可读性:

(p & (1<<(i-1)))>>(i-1);

回答by Rakesh Chaudhari

I think below soln is easy to understand & simple,

我认为下面的soln很容易理解和简单,

public static void sumOfTwoNumberUsingBinaryOperation(int a,int b)
{
    int c = a&b;
    int r = a|b;
    while(c!=0)
    {
        r =r <<1;
        c = c >>1;      
    }
    System.out.println("Result:\t" + r);    
}