按位运算符的两个数的和
我粘贴代码以使用按位运算符查找两个数字的总和。 请建议是否可以优化。 谢谢…
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); //find the nth bit of p int n2 = (q & (1<>(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;
的循环p = result; q = carry;
p = result; q = carry;
。
算法探索的另一个特点是在区分情况方面并不是很远。 在上面你也可以采取以下条件: if ((result & carry) != 0)
。
我认为优化应该在可读性领域而不是性能领域(可能由编译器处理)。
用于循环而不是while
如果您事先知道迭代次数,则for (int i=0; i<32; i++)
的习惯用法比while循环更具可读性。
将数字除以2
将数字除以2得到模数:
n1 = p % 2; p /= 2;
可能比以下更具可读性:
(p & (1<<(i-1)))>>(i-1);