问题描述
对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能。
方法一:五层循环
代码:
public class Test{
public static void main (String args[]){
for(int a1=0;a1<2;a1++){
for(int a2=0;a2<2;a2++){
for(int a3=0;a3<2;a3++){
for(int a4=0;a4<2;a4++){
for(int a5=0;a5<2;a5++){
StringBuffer s=new StringBuffer();
System.out.println(s.append(a1).append(a2).append(a3).append(a4).append(a5));
}
}
}
}
}
}
}
方法二:直接进行二进制字符串转换
public static void methodC(){
for(Integer i = 0 ;i<32;i++) {
String str = Integer.toBinaryString(i);//转二进制字符串
for(int n = str.length();n<5;n++) {
System.out.print("0");
}
System.out.println(str);
}
}
输出:
00000 00001 00010 00011 …11100 11101 11110 11111