题目:
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这32种01串。
第一种:
#include <iostream> using namespace std; int main() { int a[5] = {0,0,0,0,0}; int len = 5; for(int i=0;i<=31;i++){ //0-31数字的二进制 int count = 4; int s = i; while(s) //从后往前写数 { a[count--] = s%2; s = s/2; } for(int j=0;j<=count;j++) //补0 a[j] = 0; for(int j=0;j<len;j++) //输出 cout<<a[j]; cout<<endl; } return 0; }
第二种直接暴力:将所有案例直接输出:
#include <iostream> using namespace std; int main() { cout<<"00000"<<endl; cout<<"00001"<<endl; cout<<"00010"<<endl; cout<<"00011"<<endl; cout<<"00100"<<endl; cout<<"00101"<<endl; cout<<"00110"<<endl; cout<<"00111"<<endl; cout<<"01000"<<endl; cout<<"01001"<<endl; cout<<"01010"<<endl; cout<<"01011"<<endl; cout<<"01100"<<endl; cout<<"01101"<<endl; cout<<"01110"<<endl; cout<<"01111"<<endl; cout<<"10000"<<endl; cout<<"10001"<<endl; cout<<"10010"<<endl; cout<<"10011"<<endl; cout<<"10100"<<endl; cout<<"10101"<<endl; cout<<"10110"<<endl; cout<<"10111"<<endl; cout<<"11000"<<endl; cout<<"11001"<<endl; cout<<"11010"<<endl; cout<<"11011"<<endl; cout<<"11100"<<endl; cout<<"11101"<<endl; cout<<"11110"<<endl; cout<<"11111"<<endl; return 0; }
第三种:依据二进制规律,分别输出每一位
#include <iostream> using namespace std; int main() { for(int i=0;i<32;i++) cout<<i%32/16<<i%16/8<<i%8/4<<i%4/2<<i%2<<endl; return 0; }