蓝桥杯 BASIC-2 01字串

题干

问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:

00000

00001

00010

00011

00100

请按从小到大的顺序输出这32种01串。

输入格式
本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出

00000
00001
00010
00011
<以下部分省略>

题解

第一种思路,五层for循环

#include<iostream>
using namespace std;
int main(){
	for(int i=0;i<=1;i++)
		for(int j=0;j<=1;j++) 
			for(int k=0;k<=1;k++)
				for(int w=0;w<=1;w++)
					for(int l=0;l<=1;l++)
						cout<<i<<j<<k<<w<<l<<endl;
	return 0; 
}

第二种思路,递增的字符串刚好对应十进制的 0 ~ 31,故用 0 ~ 31转二进制,当字符串长度不足 5 位,前面补0

#include<iostream>
#include<string>   //string 常用函数 
#include<algorithm>   // reverse
using namespace std;
int main(){
	for(int i=0;i<32;i++){
		int tmp= i;
		string str;
		while(tmp){   // 对2取余 
			str += tmp%2+'0';
			tmp /=2; 
		}
		reverse(str.begin(),str.end());  // 反转字符串
		// 不够5位的字符串,在0位置补足0 
		while(str.length()<5){
			str.insert(0,"0");
		}
		cout<<str<<endl;
	}
	return 0;
}

查看题解目录

猜你喜欢

转载自blog.csdn.net/liyuanyue2017/article/details/85518265