我粘贴代码以使用按位运算符查找两个数字的总和.请建议是否可以优化.谢谢…
- 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 =携带;
算法探索的另一个特点是在区分情况方面并不是很远.在上面你也可以采取以下条件:if((result& carry)!= 0).