Topic:
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.
Ideas:
Shift Operations
PackageMath;Importjava.util.ArrayList;Importjava.util.List; Public classGraycode { PublicList<integer> Graycode (intN) {List<Integer> res =NewArraylist<integer>(); if(N < 0)returnRes; Res.add (0); intCount = 0; while(Count <N) { for(inti = Res.size ()-1; I >= 0; --i) {Res.add (Res.get (i)+ (1 <<count)); } ++count; } returnRes; } Public Static voidMain (string[] args) {//TODO auto-generated Method StubGraycode g =NewGraycode (); for(intI:g.graycode (3) ) System.out.println (i); }}
Leetcode-gray Code