标签:
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
这个题目很搞笑的,因为记得格雷码和二进制码之间是有转换关系的,所以可以直接通过这个关系来做这个题目。下面是转换关系:
class Solution: # @return a list of integers def grayCode(self, n): res = [] for i in range(1<<n): gray = i ^ i>>1 res.append(gray) return res
标签:
原文地址:http://www.cnblogs.com/KingKou/p/4318055.html