这个按位表达式有什么作用?

What does this bitwise expression do?

n & (n>>1)

我在哪里可以使用上面的表达式?我正在为使用表达式的问题做 this problem and I saw 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 中的连续值。它对 nn 向右移动一位进行按位与运算。如果 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.

首先将变量n中的位右移

>> - 按位右移

然后对移位后的位进行与运算..

& - 按位与运算。

这里完整的操作是这样发生的

考虑int n=6

因此它的二进制等价物将是 110 .. 你必须找出下一个大于或等于其二进制等价物不应包含两个连续的 1 的数字。

所以你认为 no 将是 8,因为它的二进制等价物是 1000

所以如果你执行

(n>>1) 结果将为 011

如果您执行并操作

011
110

结果将是

010 

现在追踪您的答案代码

main()
{
 int t,n;
 scanf("%d",&t);
 while(t--)
 {
    scanf("%d",&n);
    while((n&(n>>1)))
    {
        n++;
    }
    printf("%d\n",n);
 }
}