Construct N-bit gray code (recursive, object-oriented)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.