[LeetCode]题解(python):089 Gray Code

时间:2021-01-01 16:27:19

题目来源


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.

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.


题意分析


Input:

:type n: int

Output:

:rtype: List[int]

Conditions:给定一个大小n(即n bit),返回bit为n位下的Gray code序列。


题目思路


Binary Code可以直接转为Gray Code,比如Binary Code 为 1011,转为为Gray Code:

(Binary Code)1011 = 1(第一位不变), 1(第一位异或第二位,1^0), 1(第二位异或第三位,0^1), 0(第三位异或第四位,1^1) = 1110(Gray Code)

也就是(1011 >> 1) ^ 1011 = 1110, 一般化即: (i >> 1) ^ i


AC代码(Python)


 class Solution(object):
def grayCode(self, n):
"""
:type n: int
:rtype: List[int]
"""
if n <= 0:
return [0]
size = 1 << n
res = []
for i in range(size):
res.append((i>>1)^i)
return res