[LeetCode]89. Gray Code

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

分析

格雷碼序列生成問題,序列中前後連續的兩個數的二進制只有一位比特位不同,用下面這張圖表示:
這裏寫圖片描述
格雷碼有個公式,自然整數n對應的格雷碼爲:
n ^ (n/2)

源碼

class Solution {
public:
    // 格雷碼數學公式:整數n的格雷碼爲: n^(n >> 1)
    // 現在要生成所有n比特的格雷碼
    vector<int> grayCode(int n) {
        vector<int> ret;
        size_t size = 1 << n ;//2^n個自然數
        for(size_t i = 0; i < size; i++){
            ret.push_back(i ^ (i >> 1));
        }
        return ret;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章