蓝桥杯省模拟赛 01串个数
问题描述
请问有多少个长度为 24 的 01 串,满足任意 5 个连续的位置中不超过 3 个位置的值为 1。
所有长度为24的01串组合有2*24种
思路:遍历所有长度为24的01串组合,选择出符合题意的
#include<iostream>
#include<cmath>
using namespace std;
bool check(int x)
{
for(int j=0; j<24-4; ++j)
{
int cnt=0;
//检查当前5位(i到i+4)中1的个数
//用位操作 (a>>k) & 1提取第 k 位的值(0或1)
//如果当前位是1的话,cnt++
cnt += ((x>>j) & 1);
cnt += ((x>>(j+1)) & 1);
cnt += ((x>>(j+2)) & 1);
cnt += ((x>>(j+3)) & 1);
cnt += ((x>>(j+4)) & 1);
if(cnt>3) return false; //如果1的个数>3,返回false
}
return true;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int ans = 0;
//遍历所有24位二进制数 用十进制表示就是 0~2^24-1
//1<<24:1*2^24
int i;
for(i=0; i<pow(2, 24)-1; ++i)
{
if(check(i)) ans++;
}
cout<<ans;
return 0;
}