zoukankan      html  css  js  c++  java
  • 89 Gray Code

    因为是硬件出生,所以相对比较容易

    """
    89. Gray Code
    Medium
    267
    919
    
    
    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.
    
    Example 1:
    
    Input: 2
    Output: [0,1,3,2]
    Explanation:
    00 - 0
    01 - 1
    11 - 3
    10 - 2
    
    For a given n, a gray code sequence may not be uniquely defined.
    For example, [0,2,3,1] is also a valid gray code sequence.
    
    00 - 0
    10 - 2
    11 - 3
    01 - 1
    Example 2:
    
    Input: 0
    Output: [0]
    Explanation: We define the gray code sequence to begin with 0.
                 A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
                 Therefore, for n = 0 the gray code sequence is [0].
    """

    格雷码就是一种相邻两位只有一个符号差别的编码,可以减少数据误差

    格雷码有两个特点,拿三位格雷码举例

    0000,0001,0011,0010,0110,0111,0101,0100,

    1、前2位和2位格雷码相同
    2、后两位看到前半段和后半段是顺序相反的,

    所以做n位格雷码只要先做n-1位格雷码,再在最后加上后半段就行了

    class Solution:
        def grayCode(self, n):
            """
            :type n: int
            :rtype: List[int]
            """
            result = []
            #0位格雷码
            result.append(0)
            for i in range(1, n+1):
                #num是前面的数字个数也是后面的数字要加的数
                num = 2**(i-1)
                #从后向前取反方向
                result.extend((i+num for i in reversed(result)))
            return result
  • 相关阅读:
    Linux下压缩解压缩命令
    Linux挂载外部设备
    Ubuntu下安装软件的三种方式
    Linux查看和修改文件权限
    Linux命令行基础操作
    window下常用的cmd命令
    圆角进度条,带数字居中显示的圆角进度条
    上下滑动控件
    window下Jekyll+github搭建自己的博客
    PAT 团体程序设计天梯赛 L1-046 整除光棍(模拟除法)
  • 原文地址:https://www.cnblogs.com/mangmangbiluo/p/10069860.html
Copyright © 2011-2022 走看看