問題描述
請問有多少個長度為 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^24int i;for(i=0; i<pow(2, 24)-1; ++i){if(check(i)) ans++;}cout<<ans;return 0;
}