n & (n>>1)
我在哪里可以使用上面的表达式?我在做 this问题,我看到了this使用表达式的问题的解决方案。
问题-
You are given an integer n find its next greater or equal number whose
binary representation must not contain consecutive ones.
代码-
main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
while((n&(n>>1)))
{
n++;
}
printf("%d\n",n);
}
}
最佳答案
它检查 n
中的连续值。它对 n
执行按位与运算,并将 n
右移一位。如果 n
的二进制表示至少有两个相邻的,你会得到这样的东西:
n : 00001100
n>>1 : 00000110
---------------------
n & (n>>1) : 00000100
将此与原始作业进行比较:
You are given an integer n find its next greater or equal number whose binary representation must not contain consecutive ones.
关于c++ - 这个按位表达式有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31804936/