前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Gray Code

Leetcode: Gray Code

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 15:12:34
3870
发布2019-01-22 15:12:34
举报
文章被收录于专栏:给永远比拿愉快

题目: 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:

代码语言:javascript
复制
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.

Gray Code: 在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code)。格雷码当初是为了通信,现在则常用于模拟-数字转换和位置-数字转换中。

Gray Code转换方法: 递归生成码表 这种方法基于格雷码是反射码的事实,利用递归的如下规则来构造:

代码语言:javascript
复制
 1. 1位格雷码有两个码字 

 2. n位格雷码中的前2(n-1)个码字等于n-1位格雷码的码字,按顺序书写,加前缀0 

 3. (n+1)位格雷码中的后2(n-1)个码字等于n-1位格雷码的码字,按逆序书写,加前缀1 

C++参考代码(用时7ms):

代码语言:javascript
复制
class Solution
{
public:
    vector<int> grayCode(int n)
    {
        vector<int> codes;
        codes.push_back(0);
        for (int i = 0; i < n; ++i)
        {
            int one = 1 << i;//最高位的数字1
            int size = int(codes.size());
            //这个循环要倒序哦
            for (int j = size - 1; j >= 0; --j)
            {
                codes.push_back(one + codes[j]);
            }
        }
        return codes;
    }
};

异或转换 二进制码->格雷码(编码):

代码语言:javascript
复制
 1. 从0到2n-1编号 

 2. 从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0); 

格雷码->二进制码(解码): 从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。

C++代码(用时9ms):

代码语言:javascript
复制
class Solution
{
public:
    vector<int> grayCode(int n)
    {
        vector<int> codes;
        int size = 1 << n;//相当于pow(2, n)
        for (int i = 0; i < size; ++i)
        {
            codes.push_back((i >> 1) ^ i);
        }
        return codes;
    }
};

我发现把第十行的右移一位codes.push_back((i >> 1) ^ i)(用了9ms)改成除法运算codes.push_back((i / 2) ^ i)(用了6ms)运算还变快了!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015年04月11日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档