對於長度為n位的一個01(二進制)串,每一位都可能是0或1,一共有2^n種可能。它們的前幾個是:
00000
00001
00010
00011
00100
請按從小到大的順序輸出這2^n種01串。
樣例輸入
5
樣例輸出
00000
00001
00010
00011
……(共32行)
1 package com.work2021; 2 3 import java.util.Scanner; 4 5 /** 6 * @ClassName: Assignment_30 7 * @Description: one new test 8 * @author: Yu wang 9 * @date: Created in 2021/3/5 8:17 10 */ 11 public class Assignment_30 { 12 static public Scanner sc = new Scanner(System.in); 13 static public color color = new color(); 14 public static void main(String[] args) { 15 do { 16 new Assignment_30().work(); 17 System.out.println(color.color1() + "\n繼續輸入0,退出輸入1"); //循環判斷 18 } while (sc.nextInt() != 1); 19 } 20 public void work(){ 21 System.out.println(color.color1()+"輸入長度:"); 22 int n = sc.nextInt(); 23 //用for表示2^n個二進制數 24 for(int i=0;i<Math.pow(2,n);i++){ 25 //用來將整數轉換成二進制 26 String s1=Integer.toBinaryString(i); 27 //表示s1將整數轉換成二進制的長度 28 int length=s1.length(); 29 //長度等於n的情況 30 if(length==n){ 31 System.out.println(color.color2()+s1); 32 } 33 else{ 34 //cha為s1前面缺少的二進制位數 35 int cha=n-length; 36 //定義一個字符串空間 37 StringBuffer sb=new StringBuffer(s1); 38 while(cha>0){ 39 //在s1前面插入相應的0 40 sb.insert(0,"0"); 41 cha--; 42 } 43 System.out.println(color.color2()+sb); 44 } 45 } 46 } 47 }