蓝桥杯算法题库 01字串

蓝桥杯算法题库 01字串

题目

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

00000

00001

00010

00011

00100

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

输入格式
本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011
<以下部分省略>

解题思路

1、将问题理解为二进制加法,每次末尾加1,大于1向前进1。
2、具体步骤:
3、定义一个长度为5点数组;每循环x[4] + 1,x[4] 大于1向前进1。;直到首位为1的时候停止

扫描二维码关注公众号,回复: 4616042 查看本文章
//java代码

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] x = new int[5];
		for (int j = 0; j < 5; j++) {
			System.out.print(x[j]);
		}
		System.out.println();
		while (x[0]==1) {
			x[4] = x[4] + 1;
			int n = 4;
			while (x[n] > 1 && n >= 1) {
				x[n] = 0;
				x[n - 1] = x[n - 1] + 1;
				n--;
			}
			for (int j = 0; j < 5; j++) {
				System.out.print(x[j]);
			}
			System.out.println();
		}
	}

猜你喜欢

转载自blog.csdn.net/NanyouqiaoMu_/article/details/84891257