LeetCode(87) 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
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.

分析

二进制串值与格雷码值转换问题,掌握两者之间的关系,则此题便很简单。

格雷码百度百科

二进制码 ——> 格雷码 称为 编码问题:

此方法从对应的n位二进制码字中直接得到n位格雷码码字,步骤如下:
(1)对n位二进制的码字,从右到左,以0到n-1编号
(2)如果二进制码字的第i位和i+1位相同,则对应的格雷码的第i位为0,否则为1(当i+1=n时,二进制码字的第n位被认为是0,即第n-1位不变)—— 异或规则

如:

  Binary Code :1011 要转换成Gray Code

  1011 = 1(照写第一位), 1(第一位与第二位异或 1^0 = 1), 1(第二位异或第三位, 0^1=1), 0 (1^1 =0) = 1110

  其实就等于 (1011 >> 1) ^ 1011 = 1110

  
格雷码 ——> 二进制码 称为 解码问题

从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。依次异或,直到最低位。依次异或转换后的值(二进制数)就是格雷码转换后二进制码的值。

AC代码

class Solution {
public:
    vector<int> grayCode(int n) {
        //n位构成的二进制序列值为0~2^n-1

        if (n == 0)
            return vector<int>(1,0);
        //1左移n位 得到2^n
        int size = 1 << n;

        vector<int> ret;

        for (int i = 0; i < size; i++)
        {
            ret.push_back(i ^ (i >> 1));
        }

        return ret;
    }
};

GitHub测试程序源码

原文地址:https://www.cnblogs.com/shine-yr/p/5214838.html