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.
Find binary Gray Code
Two methods:
1. Recursive method:
Public classSolution { PublicList<integer> Graycode (intN) {List result=NewArraylist<integer>(); if(n = = 0) {Result.add (0); returnresult; }Else if(n = = 1) {Result.add (0); Result.add (1); returnresult; }ElseResult.addall (Graycode (n-1)); intmax = 1; for(inti = 1;i<n;i++) {Max*=2; } intSize =result.size (); for(inti = 1;i<=size;i++) {Result.add (int) Result.get (max-i) +max); } returnresult; }}
2, bit operation.
PublicList<integer> Graycode (intN) {List<Integer> ret =NewArraylist<>(); Ret.add (0); for(inti = 1, shift = 1; I <= N; i++) { //Mirror from previous 2 ^ (i-1) for(intj = shift-1; J >= 0; j--) { //Ret.get (j) ^ Shift is more efficient here's +Ret.add ((Ret.get (j) ^shift)); } Shift<<= 1; } returnret; }
Leetcode Gray Code-----java