Gray Code
The gray code is a binary numeral system where two successive values 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,[0,2,3,1]
Is also a valid Gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of Gray code sequence. Sorry about that.
Train of Thought: Get the length of the current vector each time, and the length is exactly the highest bit of the current Gray code, and then use the highest bit to be different from or to the data in the vector. Pay attention to the forward from the back, to the next group?
Class solution {public: vector <int> graycode (int n) {vector <int> res (1, 0); int I; while (n --) {int highbit = res. size (); // The highest bit of the current binary for (I = res. size ()-1; I> = 0; -- I) res. push_back (highbit | res [I]);} return res ;}};
Gray Code of leetcode