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.
1 Public classSolution {2 PublicList<integer> Graycode (intN) {3list<integer> ans =NewArraylist<integer>();4 intLen = (int) Math.pow (2, n);5 for(inti = 0; i< Len; i++){6Ans.add (i^ (i>>1) ;//According to the solution of the mathematical formula. G (n) = (b (n)/2) XOR B (n).7 }8 returnans;9 }Ten}
Binary number transcoding Gray code
(assuming that the value of binary 0 is 0 of the Gray code)
G: Gray code B: binary Code
G (n) = (b (n)/2) XOR B (n).
Take three-bit as an example:
000^000-->000
001^000-->001
010^001-->011
011^001-->010
100^010-->110
101^010-->111
110^011-->101
111^011-->100
Solution Two: recursion is available. Later in the summary.
Reference Posts:
http://blog.csdn.net/makuiyu/article/details/44926463
Http://www.cnblogs.com/peihao/p/5269151.html (the second post described is still not clear enough)
Gray Code Java Solutions