问题描述
我有一个矩阵,持有1:s或0:S,创建二进制数。其宽度为n。对于n = 2和n = 3会是这样的:
00 000
01 001
10 010
11 011
100
101
110
111
等。现在,我用下面的code产生这种。
INT行=(int)的Math.pow(2,N);
INT COL = N;
INT [] []矩阵=新INT [行] [COL];
对于(INT R = 0; R<排; R ++){
串binaryNumber =的String.Format(%+ N +的s,Integer.toBinaryString(r)的)代替('','0')。
对于(INT C = COL - 1; C> = 0; C--){
矩阵[R] [C] =的Integer.parseInt(+ binaryNumber.charAt(0));
binaryNumber = binaryNumber.substring(1);
}
}
现在我需要创建同样的事情,但灰度codeD帮助。有没有一种简便的方法来做到这一点在Java中?此外,如果有一个更聪明的方法做我在做什么上面我很想学习。
我真的没有一个线索从哪里开始,因为我已经习惯了有 toBinaryString()
帮助我。编辑:灰度code将是这样的:
00 000
01 001
11 011
10 010
110
111
101
100
您可以通过简单地改变得到灰色code
Integer.toBinaryString(R)
到
Integer.toBinaryString((R>> 1)^ R)。
有一个尝试:)
I have a matrix that holds 1:s or 0:s, creating binary numbers. Its width is n. For n = 2 and n = 3 it would look like:
00 000
01 001
10 010
11 011
100
101
110
111
and so on. Right now I'm using the following code to produce this.
int row = (int) Math.pow(2, n);
int col = n;
int[][] matrix = new int[row][col];
for (int r = 0; r < row; r++) {
String binaryNumber = String.format("%" + n + "s", Integer.toBinaryString(r)).replace(' ', '0');
for (int c = col - 1; c >= 0; c--) {
matrix[r][c] = Integer.parseInt("" + binaryNumber.charAt(0));
binaryNumber = binaryNumber.substring(1);
}
}
Now I need help with creating the same thing but gray-coded. Is there a convenient way to do this in java? Also, if there is a smarter way to do what I'm doing above I'd love to learn.
I don't really have a clue where to start since I'm used to having toBinaryString()
helping me. EDIT: The gray-code will look like this:
00 000
01 001
11 011
10 010
110
111
101
100
You can get gray code by simply changing
Integer.toBinaryString(r)
into
Integer.toBinaryString((r >> 1) ^ r)
.
Have a try:)
这篇关于填写矩阵二进制数,定期和灰色codeD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!