Try*_*ing 6 java bit-manipulation
我粘贴代码以使用按位运算符查找两个数字的总和.请建议是否可以优化.谢谢...
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;
}
Run Code Online (Sandbox Code Playgroud)
Joo*_*gen 25
想一想:
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;
}
Run Code Online (Sandbox Code Playgroud)
该递归结束,因为进位在右侧连续有更多位0(最多32次迭代).
人们可以很容易地把它写成一个循环p = result; q = carry;.
算法探索的另一个特点是在区分情况方面并不是很远.在上面你也可以采取以下条件:if ((result & carry) != 0).
| 归档时间: |
|
| 查看次数: |
16457 次 |
| 最近记录: |