java - Print 'n' binary numbers of the length 'n' with for loops -


i'm trying write code enter number 'n' , shows me 'n' binary numbers of length 'n'. sequence of numbers doesnt matter.

e.g. enter 3 (n=3)

000 001 010 011 100 101 110 111 got far

    string b1="1",b2="0";     string combination="0";     string output="0"      (int k=1; k<=n; k++) {              (int z=1; z<=n; z++)             {                 combination= b1+b2;             }         output = output+combination;          }     system.out.println(output); 

but output: 01010101010101010

there tools print binary representations of numbers in integer() class.

so n=3 want 3 sets of binary digits outputted, 3 bits in each output. tobinarystring() takes int parameter , returns "the string representation of unsigned integer value represented argument in binary (base 2)". need make adjustments proper padding in front of binary representations 2 bits in length, i.e. 0, 1, 2, 3 00, 01, 10, 11, respectively.

edit: once copied snippet actual eclipse project noticed logic padding incorrect. have fixed it. code want. think you'll have finessing amount of output digits way want it.

int n = 4; int numbits; string paddingzero = "0"; string binary;  for(int = 0; <= n; i++) {     numbits = n / 2;     if(numbits < 2)     {         numbits = 2; // binary should never display less 2 bits of digits clarity.     }      binary = integer.tobinarystring(i);     if(binary.length() < numbits)     {                   {             binary = paddingzero + binary;         }         while(binary.length() < numbits);     }      system.out.print(binary + " "); // appends string representation of binary digit paddingzeroes } 

output

@ n = 3 00 01 10 11   @ n = 4 00 01 10 11 100   @ n = 7 000 001 010 011 100 101 110 111  

once n > 8 numbits logic need change some. started.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -