Java的:如何输出的所有可能的二进制组合(256个不同的序列)? [英] Java: How to output all possible binary combinations (256 different sequences)?
问题描述
我需要创建输出所有可能的二进制组合的功能(2 ^ 8 = = 256个不同的8位序列)。我真的难倒这一点。我有嵌套循环做到这一点,而且我不知道如何去做。下面是我试过至今。有人告诉我,我可以写使用8个嵌套的循环,每一个从0到1走这计划;另外,我可以尝试用位操作运营商做到这一点。
I need to create a function that outputs all possible binary combinations (2^8 == 256 different sequences of 8 bits.). I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far. I was told that I could write this program using 8 nested loops, each one going from 0 to 1; Also, I could try to do this with bit manipulation operators.
虽然我下面的显然是错误的,我尽我所能来证明我至少尝试过这一点。我还需要投入新的生产线的每一个右括号后,到输出分开。
Although what I have below is obviously wrong, I tried my best to show that I at least tried this. I also need to put new line's after each closing bracket, to separate the output.
输出应该是这样的:
00000000
00000001
00000010
00000011
00000100
...
11111110
11111111
public static void outputBinary(){
int[][][][][][][][] num = new int[2][2][2][2][2][2][2][2];
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.print(num[i][j][k][l][m][n][o][p]);
} }}}}}}}
}
有关寻找的感谢。
推荐答案
没有必要的阵列。这里是一个轻微修改您的code将输出所有排列。
No need for the array. Here is a slight modification to your code that will output all the permutations.
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
System.out.println("" + i + j + k + l + m + n + o + p);
}
}
}
}
}
}
}
}
你的有无的使用嵌套循环?因为这是十分容易,当你随便拿的事实,即二进制重新$ P $ 0所有号码通过255盖psentation每个排列。
Do you have to use nested loops? Because this is trivially easy when you simply take advantage of the fact that the binary representation of all the numbers from 0 through 255 cover every permutation.
for (int i=0; i<256; i++) {
System.out.println(Integer.toBinaryString(i));
}
这篇关于Java的:如何输出的所有可能的二进制组合(256个不同的序列)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!