Problem:
The N-bit gray code is printed recursively (the next two encodings differ only by one digit):
The problem is attributed to the existing Gray code of the top n bits, how to construct the gray code of the n+1 bit?
Workaround: Recursive construction of gray code set and.
Recursive exit: n = 1; This time gray code {0,1}
N+1:n+1 bit Gray code = N-bit gray code (sequential) +0,n Gray Code reverse +1 (n-bit gray code sequence the last encoding is the same as the reverse order, the first encoding is the same code, which can be added 0, 12 encoding is still only one bit different)
Public classgc{int[] G;// intN; intSIZE; GC (intN) { This. N =N; SIZE=(int) Math.pow (2, N); G=Createg (g,n); } Public int[] Createg (int[] g,intN) {//A new gray code set g recursive construction by the original gray code set G if(N <1){ return NULL; } if(N = = 1) {g=New int[2] [1]; g[0][0] = 0; g[1][0] = 1; returnG; } g= Createg (g,n-1); SIZE=(int) Math.pow (2, N); G=New int[Size][n]; intn =n-1;//the number of bits of the original gray code for(intI =0;i<size/2;i++) {//Order for(intj=0;j<n;j++) {G[i][j]=G[i][j]; } g[i][n-1] = 0; } for(inti = size/2;i<size;i++) {//Reverse for(intj=0;j<n;j++) {G[i][j]= g[size-1-i] [j]; } g[i][n-1] = 1; } returnG; } Public voidShow () { for(intI =0;i<size;i++){ for(intj=0;j<n;j++) {System.out.print (G[i][j]+" "); } System.out.println (); } } Public Static voidMain (string[] args) {intN =NewInteger (args[0]). Intvalue (); GC G=NewGC (N); G.show (); return; }}
View Code
Construct N-bit gray code (recursive, object-oriented)