1. 程式人生 > >LeetCode: Gray Code [089]

LeetCode: Gray Code [089]

如果 ott while 規則 1.4 height p s define family

【題目】


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 - 0
01 - 1
11 - 3
10 - 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.




【題意】

本題是有關格雷碼轉換的,知道二進制轉換為格雷碼的轉換規則,本題就很easy了。
給定二進制下的位數n, 要求得到格雷碼序列,並輸出每一個格雷碼相應的十進制表示。相鄰格雷碼之間僅僅有一位不同。


對於輸入的n,格雷碼序列可能有多個,題目要求輸出任一個序列就可以。
序列必須以0開始。


【思路】

n位二進制可表示2^n個數。因此格雷碼序列長度即為2^n
我們僅僅需從小到大把二進制轉換成相應的格雷碼就可以。轉換規則例如以下:
如果二進制數為x, 則其相應的格雷碼為x>>1^x
即x和其本身向右移動一位後的結果做抑或運算。

【註意。n=0是本題覺得它能表示一個值0】


【代碼】

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;
    }
};


LeetCode: Gray Code [089]