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.
Gray code Definition: Baidu Encyclopedia
Binary Gray Code
0 000 000
1 001 001
2 010 011
3 011 010
4 100 110
5 101 100
6 110 101
7 111 100
The method is: the binary code from the right to the left, the first and the next one to do the XOR or Operation , the leftmost one remains motionless.
Then move the 110 right to 011, and then the XOR
110^011=101 This dislocation of XOR, just to achieve the demand
Gray code decoding when the reverse can be, from the left second bit to start with the next XOR.
Code:
class solution { public <int > Graycode (int n) {vector <int > res; Res.push_back ( 0 ); for (int i= 1 ;i< (i) {Res.push_back ((i >>1 ) ^i); return res; }};
Gray Code (grey code)