The gray code is a binary numeral system where two successive values differ in only one bit.post
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.spa
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:code
00 - 0 01 - 1 11 - 3 10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.blog
For example, [0,2,3,1]
is also a valid gray code sequence according to the above definition.ip
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.it
本題是有關格雷碼轉換的,知道二進制轉換爲格雷碼的轉換規則,本題就很easy了。
對於輸入的n,格雷碼序列可能有多個,題目要求輸出任一個序列就能夠。
序列必須以0開始。io
class Solution { public: vector<int> grayCode(int n) { vector<int> result; int size=1<<n; //一共可以表示2^n個數 int x=0; while(x<size){ result.push_back(x>>1^x); //轉換成相應格雷碼 x++; } return result; } };