问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。它们的前几个是:
00000
00001
00010
00011
00100
请按从小到大的顺序输出这32种01串。
输入格式
本试题没有输入。
输出格式
输出32行,按从小到大的顺序每行一个长度为5的01串。
样例输出
00000
00001
00010
00011
<以下部分省略>
00001
00010
00011
<以下部分省略>
这个问题是输出问题,当然,最简单的方法就是暴力输出,即用System.out.println()语句一一列举出来。
当然测试系统并不希望我们这样做法。
另一种方法,就是用5个循环的方式来做:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//Scanner input = new Scanner(System.in);
int a, b, c, d, e;
for (a = 0; a < 2; ++a)
for (b = 0; b < 2; ++b)
for (c = 0; c < 2; ++c)
for (d = 0; d < 2; ++d)
for (e = 0; e < 2; ++e) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print(d);
System.out.println(e);
}
}
}
还有一种方式,利用十进制转二进制的方式:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 32; i++) {
System.out.print(i % 32 / 16);
System.out.print(i % 16 / 8);
System.out.print(i % 8 / 4);
System.out.print(i % 4 / 2);
System.out.println(i % 2);
}
}
}
结果输出:
00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111