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

题目来源


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)


 1 class Solution(object):
 2     def grayCode(self, n):
 3         """
 4         :type n: int
 5         :rtype: List[int]
 6         """
 7         if n <= 0:
 8             return [0]
 9         size = 1 << n
10         res = []
11         for i in range(size):
12             res.append((i>>1)^i)
13         return res

 

posted @ 2016-04-15 13:32  loadofleaf  Views(225)  Comments(0Edit  收藏  举报