問題描述
對於長度爲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