我粘贴代码以使用按位运算符查找两个数字的总和。请建议是否可以优化。谢谢...
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 次迭代)。
人们可以轻松地将其写为一个循环p = result; q = carry;
.
算法探索的另一个特点是在区分情况方面不会走得太远。
上面你还可以采用以下条件:if ((result & carry) != 0)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)