蓝桥杯:基础练习 01字串(java)

试题 基础练习 01字串

资源限制

时间限制:1.0s 内存限制:256.0MB

问题描述

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

00000

00001

00010

00011

00100

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

输入格式

本试题没有输入。

输出格式

输出32行,按从小到大的顺序每行一个长度为5的01串。

样例输出

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

思路:

使用Integer.toBinaryString()将十进制整数转换为二进制字符串,再判断长度是否能整除5,在前面加0输出

public class 字串01 {
	public static void main(String[] args) {
		
		for(int i = 0; i <= 31; i++) {
			String s = Integer.toBinaryString(i);
			int len = s.length();
			switch(len % 5) {
			case 1: s = "0000" + s;break;
			case 2: s = "000" + s;break;
			case 3: s = "00" + s;break;
			case 4: s = "0" + s;break;
			case 0: break;
			}
			System.out.println(s);
		}
	}
}

另一种方法,不用判断加0,也可以直接使用printf输出指定格式的整数:

public class 字串01 {
	public static void main(String[] args) {
		
		for(int i = 0; i <= 31; i++) {
			String s = Integer.toBinaryString(i);
			int n = Integer.parseInt(s);
			System.out.printf("%05d\n",n);
		}
	}
}
发布了35 篇原创文章 · 获赞 26 · 访问量 7151

猜你喜欢

转载自blog.csdn.net/qq_42804736/article/details/104960882