java – 使用按位运算符的两个数的和
发布时间:2020-12-15 02:53:21 所属栏目:Java 来源:网络整理
导读:我粘贴代码以使用按位运算符查找两个数字的总和.请建议是否可以优化.谢谢… public static int getSum(int p,int q){int carry=0,result =0;for(int i=0; i32; i++){ int n1 = (p (1(i)))(i); //find the nth bit of p int n2 = (q (1(i)))(i); //find the n
我粘贴代码以使用按位运算符查找两个数字的总和.请建议是否可以优化.谢谢…
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). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |