-
complete the code
Code:
for (int i = 0; i <= 1 ; i++)
for (int j = 0; j <= 1; j++)
for (int k = 0; k <= 1; k++)
System.out.println(""+i+j+k);
The above code prints out:
110
111
Complete the following code so that it produces the same output as the above
code.
Code:
for (int i = 0; i < 8; i++)
System.out.println(" "+ );
I cannot get it how can I reduce 8 lines to 2 to make same as above.
Thanks
-
Re: complete the code
Better to show your code with good indentation style so that it's readable:
Code:
for (int i = 0; i <= 1; i++)
for (int j = 0; j <= 1; j++)
for (int k = 0; k <= 1; k++)
System.out.println("" + i + j + k);
And this will print out a bit more than you show. In fact it prints out:
Code:
000
001
010
011
100
101
110
111
which is the binary representation of the ints from 0 to 7.
So what you need is some way to convert a number to its binary equivalent and then print it with a char width of 3, and with padding 0's on the left if the number is < 3 char in width. The first place I looked was at the Formatter#format method which is most often used as System.out.printf, but that doesn't do binary, only decimal, octal and hex. So I next created this hack:
Code:
for (int i = 0; i < 8; i++) {
String binaryString = Integer.toBinaryString(i);
int decimalHack = Integer.parseInt(binaryString);
System.out.printf("%03d%n", decimalHack);
}
which works, but it's cheating.
But seriously as to your problem, you need to figure out how to convert your number to its binary representation, and then simply pad those 0's to the left of the String if the String length is < 3. You should be able to figure this out on your own.
Luck!
-
Re: complete the code
My mistake, I made an error in the code formatting thats why it was showing 110 and 111 in the console. Now I am working on it.
Thanks