我不了解LeetCode上关于格雷码的解决方案

时间:2018-06-14 11:21:01

标签: c++ algorithm binary

以下是描述:

******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.****

实际上这一点对我来说是一件全新的事情,所以我看一下WIKI的介绍,然后我找到了一个解决方案(可能叫做 Mirror Construct Methond ),这是一张关于它的图表:Mirror。并且在这个方法中有代码编写:

// Mirror arrangement
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res{0};
        for (int i = 0; i < n; ++i) {
            int size = res.size();
            for (int j = size - 1; j >= 0; --j) {
                res.push_back(res[j] | (1 << i));
            }
        }
        return res;
    }
};

现在的问题是,我无法弄清楚*res.push_back(res[j] | (1 << i))的含义是什么。我不能很好地理解和使用逻辑字符。

1 个答案:

答案 0 :(得分:0)

res.push_back(res[j] | (1 << i));

传递给res.push_back()的参数是res [j]的内容,并设置了第i位。

如果i为2,则设置表示值4的位。该参数还将具有在res [j]设置中设置的所有位。