问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。
它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这 32 种01串。
输入格式
本试题没有输入。
输出格式
输出 32 行,按从小到大的顺序每行一个长度为 5 的01串。
样例输出
00000
00001
00010
00011
<以下部分省略>
题解一
枚举:
#include <iostream>
using namespace std;
int main()
{
for (int a = 0; a <= 1; a ++)
for (int b = 0; b <= 1; b ++)
for (int c = 0; c <= 1; c ++)
for (int d = 0; d <= 1; d ++)
for (int e = 0; e <= 1; e ++)
cout << a << b << c << d << e << endl;
return 0;
}
题解二
位运算:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 32; i ++)
{
for (int j = 4; j >= 0; j --)
cout << (i >> j & 1); // i 的二进制排列中,第 j 位是不是 1
cout << endl;
}
return 0;
}