1.问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这32种01串。
2.bitset题解
省去一般的模拟暴力解法,说一下c++的bitset巧解做法
#include<bitset> 引入即可
举例:
bitset<4> bitset1; //无参构造,长度为4,默认每一位为0
bitset<8> bitset2(12); //长度为8,二进制保存,前面用0补充
string s = "100101";
bitset<10> bitset3(s); //长度为10,前面用0补充
char s2[] = "10101";
bitset<13> bitset4(s2); //长度为13,前面用0补充
cout << bitset1 << endl; //0000
cout << bitset2 << endl; //00001100
cout << bitset3 << endl; //0000100101
cout << bitset4 << endl; //0000000010101
参考博客
3.参考代码
如果是n位的话,化成 i<2^n 条件即可
#include <iostream>
#include<bitset>
using namespace std;
int main(){
for(int i=0;i<32;i++){
bitset<5> bs(i);
cout<<bs<<endl;
}
return 0;
}