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 - 001 - 111 - 310 - 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