• LeetCode: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.                                                                                    本文地址

    分析:关于格雷码请参考wiki百度百科

    二进制转格雷码:gray = (binary) xor (binary >> 1)

    代码如下:

     1 class Solution {
     2 public:
     3     vector<int> grayCode(int n) {
     4         //注意n = 0时,输出{0}而不是空数组
     5         int num = 1<<n;
     6         vector<int> res;
     7         res.reserve(num);
     8         for(int i = 0; i < num; i++)
     9             res.push_back(i^(i>>1));
    10         return res;
    11     }
    12 };

    这篇文章有一个对格雷码很有意思的解释

    顺便科普一下解码(格雷码 转 二进制码)方法(摘自百度百科):

    格雷码→二进制码(解码):
    从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。依次异或,直到最低位。依次异或转换后的值(二进制数)就是格雷码转换后二进制码的值。
    公式表示:
    (G:格雷码,B:二进制码)
    原码:p[n:0];格雷码:c[n:0](n∈N);编码:c=G(p);解码:p=F(c);
    书写时按从左向右标号依次减小,即MSB->LSB,编解码也按此顺序进行
    举例:
    如果采集器器采到了格雷码:1010
    就要将它变为自然二进制:
    0 与第四位 1 进行异或结果为 1
    上面结果1与第三位0异或结果为 1
    上面结果1与第二位1异或结果为 0
    上面结果0与第一位0异或结果为 0
    因此最终结果为:1100 这就是二进制码即十进制 12
    当然人看时只需对照表1一下子就知道是12

    【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3451938.html

  • 相关阅读:
    css面试题目
    5. React-Router05 BrowserRouter 和hashrouter
    5. React-Router03 withRouter
    5. React-Router01
    CVE-2019-0708—微软RDP远程桌面代码执行漏洞复现
    正则表达式学习汇总
    CTF---PHP安全考题
    快速搭建主动诱导型开源蜜罐框架系统--hfish
    python--爬取网页存在某字符
    Linux 实用指令之查看端口开启情况
  • 原文地址:https://www.cnblogs.com/TenosDoIt/p/3451938.html
Copyright © 2020-2023  润新知