n&1和n >> = 1是什么意思?

时间:2020-08-07 17:07:52

标签: c++ c++11

我正在做这个练习:https://www.hackerrank.com/challenges/30-binary-numbers/problem,我在网上找到了这个“智能”代码,但是我不明白n&1和n >> = 1的条件在这里做什么。

 //C++ program to convert a decimal
// number to binary number

#include <iostream>
using namespace std;

int main()
{
    int n,count=0,max=0;
    cin >> n;

    while(n)
    {
        if (n&1)
            count++;
        else
            count = 0;
        if (max < count)
            max = count;
        n>>=1;
    }
    cout << max;

    return 0;
}

2 个答案:

答案 0 :(得分:1)

if (n&1)

通过按位与检查n是否为奇数。

n>>=1;

n的位向右移一位。

答案 1 :(得分:0)

&是按位与运算符,其计算表达式为true或false(当表达式是有条件的时),它与x % 2非常相似,即以下条件:

if (n & 1) {
    //...
}

// is equal to

if (n % 2) {
    // ...
}

OTOH,n >>= 1向右移n一点。

相关问题