力扣—gray code (格雷編碼) python實現

題目描述:編碼

中文:spa

格雷編碼是一個二進制數字系統,在該系統中,兩個連續的數值僅有一個位數的差別。code

給定一個表明編碼總位數的非負整數 n,打印其格雷編碼序列。格雷編碼序列必須以 0 開頭。blog

英文:it

The gray code is a binary numeral system where two successive values differ in only one bit.io

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.class

class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        res = [0]
        for i in range(n):
            res += [ (1 << i) + res[-j-1] for j in range(1 << i) ]
        return res

 

 

題目來源:力扣object

相關文章
相關標籤/搜索