Leetcode 89 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

 

We add 2^i to the corresponding number in the reversed copy of the previous array, then append it to the array every time.

class Solution:
    # @return a list of integers
    def grayCode(self, n):
        a = [0]
        for i in range(n):
            a += [x + 2**i for x in a[::-1]]
        return a

 

posted @ 2015-07-04 15:49  lilixu  阅读(121)  评论(0编辑  收藏  举报