There are already tools to print binary representations of numbers in the Integer()
class.
So for n=3
you want 3 sets of binary digits outputted, with 3 bits in each output. toBinaryString()
takes an int
parameter and returns "the string representation of the unsigned integer value represented by the argument in binary (base 2)". You will need to make some adjustments to get the proper padding in front of binary representations that are only 2 bits in length, i.e. 0, 1, 2, 3 which are 00, 01, 10, 11, respectively.
Edit: Once I copied my snippet to an actual Eclipse project I noticed my logic for padding was incorrect. I have fixed it. This code is almost exactly what you want. But I think you'll have to do some finessing to get the amount of output digits the way you want it.
int n = 4;
int numBits;
String paddingZero = "0";
String binary;
for(int i = 0; i <= n; i++)
{
numBits = n / 2;
if(numBits < 2)
{
numBits = 2; // Binary should never display less than 2 bits of digits for clarity.
}
binary = Integer.toBinaryString(i);
if(binary.length() < numBits)
{
do
{
binary = paddingZero + binary;
}
while(binary.length() < numBits);
}
System.out.print(binary + " "); // Appends the String representation of the binary digit to the 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 the numBits logic will need to change some. This will get you started.