按位运算符的两个数的和 [英] Sum of two numbers with bitwise operator

查看:130
本文介绍了按位运算符的两个数的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}


推荐答案

在整个位中思考:

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;
}

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

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

可以轻松地将其写为带有 p = result的循环; q = carry;

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

算法探索的另一个特点是在区分情况方面并不是很远。
以上您还可以采取以下条件: if((result& carry)!= 0)

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

这篇关于按位运算符的两个数的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆