仅使用按位运算符将两个整数相加?

在C#中,是否可以执行两个32位整数的和而不使用if..else,循环等?

也就是说,是否可以仅使用按位运算OR(|),AND(&),XOR(^),NOT(!),左移(<<)和右移(>>)来完成?

回答:

这是您娱乐的例子

unsigned int myAdd(unsigned int a, unsigned int b)

{

unsigned int carry = a & b;

unsigned int result = a ^ b;

while(carry != 0)

{

unsigned int shiftedcarry = carry << 1;

carry = result & shiftedcarry;

result ^= shiftedcarry;

}

return result;

}

该循环可能会展开。它执行的次数取决于操作数中设置的位数,但永远不会大于的宽度unsigned

int。一旦carry成为0,接下来的迭代就不会改变任何东西。

以上是 仅使用按位运算符将两个整数相加? 的全部内容, 来源链接: utcz.com/qa/410638.html

回到顶部