Problem: Gray code refers to a set of number of codes, if any two adjacent code only one binary number is different, this code is called Gray Code, please write a function, using recursive method to generate N-bit gray code.
Given an integer n, return the gray code of N-Bits, in order from 0 onwards.
Test examples:
1
return: ["0", "1"]
For example: when n = 2 o'clock, the gray code is: {00,01,11,10}
When n = 3 o'clock, Gray code is: {000,001,010,011,111,110,101,100}
Remember before the digital logic course should be learned. First known as the size of N, we can know that it corresponds to the number of gray code is 2^n, so the size of the returned array is 2^n. Then, the gray code of n must be related to the Gray Code of n-1. Therefore, we should start from 1, in turn, to know the gray Code of N, which is a recursive topic.
Key to analyze: Known n-1 Gray Code, then N of the Gray Code of the first and length-i-1 bits can be determined, respectively, plus 0 and 1.
Code:
ImportJava.util.*; Public classGraycode { PublicString[] Getgray (intN) {//Write code hereString[] s =NewString[2]; s[0] = "0"; s[1] = "1"; if(n = = 1) returns; intt = 2; while(T <=N) {s=Getgraycode (S, t); T++; } returns; } PublicString[] Getgraycode (string[] Last,intN) {string[] res=Newstring[(int) Math.pow (2, N)]; for(inti=0; i<last.length; i++) {Res[i]= "0" +Last[i]; Res[res.length-1-i] = "1" +Last[i]; } returnRes; }}
The realization of gray code