"089-gray Code (Gray code)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
The gray code is a binary numeral system where the successive values are differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A Gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 001 - 111 - 310 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, [0,2,3,1] was also a valid gray code sequence according to the above definition.
For now, the judge are able to judge based on one instance of gray code sequence. Sorry about that.
Main Topic
Given n, a gray code table with an output length of n.
Thinking of solving problems
Recursive Generation Code table
This method is based on the fact that Gray code is a reflection code, using the following rules of recursion to construct:
1-bit gray code with two code words
(n+1) Bit gray code in the first 2n code word equal to the code word of the N-bit gray code, in order to write, prefixed by 0
(n+1) Bit gray code in the back 2n code word equals n-bit gray code word, in reverse order, plus prefix 1
Code Implementation
Algorithm implementation class
Import Java.util.linkedlist;import java.util.List; Public classSolution { PublicList<integer>Graycode(intN) {list<integer> result =NewLinkedlist<> ();if(N >=0) {//The first half of gray codeResult.add (0);//Gray code highest bit value (not 0 o'clock) intt =1;//each outer loop is calculated with a i+1 bit of gray code table, which corresponds to the first half of the Gray Code table with a length of i+1 bits for(inti =0; I < n; i++) {//The length is the second half of the i+1-bit Gray code table, the first half of which is given by the Gray Code table of length I for(intj = result.size ()-1; J >=0; j--) {Result.add (result.Get(j) ^ t); }//Highest bit right shiftT <<=1; } }returnResult }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47290709"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "089-gray Code (Gray code)"