对于长度为n的一个01串,每一位都可能是0或1,
一共有2n种可能。请按从小到大的顺序输出这2n种01串。
Input
包含多组数据,每组数据占一行,每行一个正整数n(0<n<32)
Output
对于每组输入数据,按从小到大的顺序输出2^n行,
每行一个长度为n的01串
Sample Input
1
2
3
Sample Output
0
1
00
01
10
11
000
001
010
011
100
101
110
111
思路:题里有次幂啊,进制啥的,想办法往这边写…
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
for (int i = 0; i < Math.pow(2, n); i++) { //2的n次幂
String string = Integer.toBinaryString(i); //十进制转二进制
int num = string.length();
for (int j = 0; j < n - num; j++) { //n-num,求得前面几位,补齐0
string = "0" + string;
}
System.out.println(string);
}
}
}
下面这个是我大哥南墙的递归解法,属实看不懂哈哈哈哈哈
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
f(sc.nextInt(), "");
}
}
public static void f(int step, String s) {
if (step == 0) {
System.out.println(s);
return;
}
f(step - 1, s + "0");
f(step - 1, s + "1");
}