题解 P5660 【数字游戏【民间数据】】
这里是墨攸,平生没有什么爱好,就喜欢刷水题
给你们介绍一种很神奇的做法(虽然有点多此一举qwq):
先上代码:
#include<bits/stdc++.h>
#define orz 0
#define inf 0x3f3f3f3f
using namespace std;
int n, ans;
char c;
int main()
{
for(int i = 1; i <= 8; i ++)
{
scanf("%c", &c);
n = (n << 1) + (c - '0');
}
while(n)
{
n &= n - 1;
ans ++;
}
printf("%d", ans);
return orz;
}
这个代码是什么原理呢
首先,我们把这个
for(int i = 1; i <= 8; i ++)
{
scanf("%c", &c);
n = (n << 1) + (c - '0');
}
每次把
那么计算又是什么原理?
我们看这句代码:
n &= n - 1;
首先,
这会导致什么结果呢,我们来举个例子说明:
比如 :
10100(2) - 1 = 10011(2)
1010010000(2) - 1 = 1010001111(2)
101000000(2) - 1 = 100111111(2)
如上所见,我们找到了最低位的那个
我们只需要把原来的数 和 减一后的数 与运算一下,就可以把后面的
再如上面的例子:
10100(2) & 10011(2) = 10000(2)
1010010000(2) & 1010001111 = 1010000000(2)
101000000(2) & 100111111(2) = 100000000(2)
很明显,我们每次操作都使得原
所以我们只需要不断操作,直到原数为
于是有了如上代码。
#include<bits/stdc++.h>
#define orz 0
#define inf 0x3f3f3f3f
using namespace std;
int n, ans;
char c;
int main()
{
for(int i = 1; i <= 8; i ++)
{
scanf("%c", &c);
n = (n << 1) + (c - '0'); //转化为2进制数
}
while(n)
{
n &= n - 1; //每次操作
ans ++; //记录操作次数
}
printf("%d", ans);
return orz;
}