java – 使用按位运算符的两个数的和

前端之家收集整理的这篇文章主要介绍了java – 使用按位运算符的两个数的和前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我粘贴代码以使用按位运算符查找两个数字的总和.请建议是否可以优化.谢谢…
  1. public static int getSum(int p,int q)
  2. {
  3. int carry=0,result =0;
  4. for(int i=0; i<32; i++)
  5. {
  6. int n1 = (p & (1<<(i)))>>(i); //find the nth bit of p
  7. int n2 = (q & (1<<(i)))>>(i); //find the nth bit of q
  8.  
  9. int s = n1 ^ n2 ^ carry; //sum of bits
  10. carry = (carry==0) ? (n1&n2): (n1 | n2); //calculate the carry for next step
  11. result = result | (s<<(i)); //calculate resultant bit
  12. }
  13.  
  14. return result;
  15. }

解决方法

想一想:
  1. public static int getSum(int p,int q)
  2. {
  3. int result = p ^ q; // + without carry 0+0=0,0+1=1+0=1,1+1=0
  4. int carry = (p & q) << 1; // 1+1=2
  5. if (carry != 0) {
  6. return getSum(result,carry);
  7. }
  8. return result;
  9. }

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

人们可以很容易地把它写成一个p = result的循环; q =携带;

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

猜你在找的Java相关文章