对于长度为n位的一个01(二进制)串,每一位都可能是0或1,一共有2^n种可能


对于长度为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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM