我正在做这个练习: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;
}
答案 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
一点。