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

标签 c++ bitwise-operators

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/

相关文章:

c++ - 指向对象的全局指针导致访问冲突?

c++ - 为什么是0x7FFFFFFFull | (1 << 31) 在 C++ 中返回 0xFFFFFFFFFFFFFFFF?

C# - 大整数的按位运算

c++ - 模板类型的成员枚举类作为函数参数

c++ - 如何返回作用域锁?

c++ - "new Classname*[]"是什么意思?

c++ - 我应该将关键字 `extern` 添加到常量的定义中以在源文件之间共享吗?

c - 如何在C中检查16位地址中的每一位

c - C 中的 stdbool.h bool 类型按位异或 ^ 和赋值

mysql - 如何在sequelize中执行位操作