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
  • 相关阅读:
    PHP $_POST 变量
    PHP $_GET 变量
    PHP 完整表单实例
    PHP 表单
    PHP 表单
    PHP 表单验证
    00_前情回顾
    18_今日回顾
    VMware 12PRO安装Mac OS X 10.10.5
    05_传智播客iOS视频教程_第一个OC程序
  • 原文地址:https://www.cnblogs.com/mangmangbiluo/p/10069860.html
Copyright © 2011-2022 走看看