基礎訓練:01訓練

問題描述

對於長度爲5位的一個01串,每一位都可能是0或1,一共有32種可能。它們的前幾個是:

00000

00001

00010

00011

00100

請按從小到大的順序輸出這32種01串。

輸入格式
本試題沒有輸入。
輸出格式
輸出32行,按從小到大的順序每行一個長度爲5的01串。
樣例輸出
00000
00001
00010
00011
<以下部分省略>

//通過進制的計算,對每一位的數字進行賦值
class Main_1{
	public static void main(String[] args){
		int n1=0,n2=0,n3=0,n4=0,n5=0;  
        for(int i=0;i<32;i++){  
            if (i%2==0)n1=0;  
            else n1=1;  
            if (i/2%2==0)n2=0;  
            else n2=1;    
            if (i/4%2==0)n3=0;  
            else n3=1;  
            if (i/8%2==0)n4=0;  
            else n4=1;  
            if (i/16%2==0)n5=0;  
            else n5=1;  
            System.out.println(n5+""+n4+""+n3+""+n2+""+n1);  
        }  
	}
}


//通過五個循環對每一位數字循環0和1,進行排列
class Main_2{
	public static void main(String[] args){
		int n1, n2, n3, n4, n5;
		for(n1 = 0;n1 <= 1;n1++){
			for(n2 = 0;n2 <= 1;n2++){
				for(n3 = 0;n3 <= 1;n3++){
					for(n4 = 0;n4 <= 1;n4++){
						for(n5 = 0;n5 <= 1;n5++){
							System.out.println(n1+ "" + n2+ "" + n3+ "" + n4+ "" + n5);
						}
					}
				}
			}
		}
	}
}


//利用java中的Integer.toBinaryString將0~32數轉換成二進制並存進list中
import java.util.*;
class Main_3{
	public static void main(String[] args){
		List<String> lists = new ArrayList<String>();
		for(int i = 0;i < 32;++i){
			String str = Integer.toBinaryString(i);
			if(str.length() == 1)
			lists.add("0000"+ str);
			else if(str.length() == 2)
				lists.add("000"+ str);
			else if(str.length() == 3)
				lists.add("00"+ str);
			else if(str.length() == 4)
				lists.add("0"+ str);
			else lists.add(str);
		}
//		lists.forEach(list->System.out.println(list));
		for (String list : lists) {
			System.out.println(list);
		}
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章