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, was [0,2,3,1] 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.
Problem Solving Ideas:
Gray code, learn the principle of communication children's shoes should not be unfamiliar, but gray code generation method is not as described in the topic, the following popular science under the Gray Code generation method:
N=1 Get 0 1
n=2 get 00 01 11 10 (note, 11 and 10 except for the sign bit, and 00 01 symmetrical)
N=3 Get 000 001 011 010 110 111 101 100 (back four bits in addition to the sign bit, and the first four bits symmetrical)
N=4 in turn
Knowing the build process of gray code, the Java implementation is as follows:
static public list<integer> Graycode (int n) { list<integer> list=new arraylist<integer> (); for (int i=0;i<math.pow (2, n); i++) { int result=0,num=i,temp=n; while (temp>1) { if (Num>=math.pow (2, temp-1)) { num= (int) (2*MATH.POW (2, temp-1)-num-1); Result+=math.pow (2, temp-1); } temp--; } Result+=num; List.add (result); } return list; }
At the same time, the subject has a very concise wording, as follows:
Public list<integer> Graycode (int n) { list<integer> res = new arraylist<integer> (); for (int i = 0; i < (1<<n); ++i) Res.add (i ^ (i>>1)); return res; }
Java for Leetcode 089 Gray Code