在 C# 中,是否可以在不使用 if..else、循环等的情况下执行两个 32 位整数的求和?
也就是说,是否可以仅使用按位运算 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
. Once carry
变成0
,下一次迭代不会改变任何东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)