我正在尝试仅使用按位和某些运算符(包括 !
)来复制循环的功能~
&
^
|
+
<<
>>
int loop(int x) {
for (int i = 1; i < 32; i += 2)
if ((x & (1 << i)) == 0)
return 0;
return 1;
}
但是我不确定如何仅使用这些运算符来复制循环的累积性质。我明白转移 <<
>>
会让我乘法和除法。但是使用 !
进行操作~
&
^
~
事实证明更加困难。有什么建议吗?
http://www.tutorialspoint.com/cprogramming/c_operators.htm
编辑: 我了解如何实现位的添加,但不知道如何在不先调用 while 或 for 循环的情况下实现这样的输出。
最佳答案
也许这可以帮助:
int loop(int x) {
x = x & 0xaaaaaaaa; // Set all even numbered bits in x to zero
x = x ^ 0xaaaaaaaa; // If all odd numbered bits in x are 1, x becomes zero
x = !x; // The operation returns 1 if x is zero - otherwise 0
return x;
}
关于c++ - 仅使用按位运算符复制 for 循环的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38433765/