题目链接
https://leetcode.com/problems/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
题目大意
给出一个非负数,返回从0到这个数的格雷码
解题思路
格雷码的生成,采用数学的方法
https://zh.wikipedia.org/wiki/格雷码
代码
class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
ans = []
size = 1 << n
for i in range(size):
ans.append((i >> 1) ^ i)
return ans