C#版 - Leetcode 89. 格雷编码 - 题解

C#版 - Leetcode 89. 格雷编码 - 题解

在线提交: https://leetcode-cn.com/problems/gray-code/

题目描述


格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。

给定一个代表编码总位数的非负整数 n,打印格雷码序列。格雷码序列必须以 0 开头。

例如,给定 n = 2,返回 [0,1,3,2]。其格雷编码是:
00 - 0
01 - 1
11 - 3
10 - 2

说明:

对于给定的 n,其格雷编码的顺序并不唯一(因此返回结果的顺序不重要,可使用Vector或List)。

例如 [0,2,3,1] 也是一个有效的格雷编码顺序。



思路:
格雷码有个相应的数学公式,整数i的格雷码是i^( i 2 )。而此题并没要求返回结果中的值的严格顺序。
于是只需遍历从0 2 n -1的所有整数i,使用公式将其转换为格雷码,添加到List中即可。

已AC代码:

public class Solution
{
    public IList<int> GrayCode(int n)
    {            
        int len = 1<<n;
        IList<int> res = new List<int>(len);
        for (int i = 0; i < len; i++)
        {
            res.Add(i ^ (i >> 1));
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/yanglr2010/article/details/80632322