Gray Code Leetcode Python

来源:互联网 发布:四小票采集软件 编辑:程序博客网 时间:2024/05/19 22:50

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.

这道题目用Bit 操作来解决。Gray code的特点是两两之间只差一位其余都相同,所以我们可以考虑移位操作

题目给出了n ,因此我们可以得到graycode的最大长度为2的n方。

我们操作时候只需要将index向右移位一位再与index求xor就可以得到解。gray code有多种,只要满足两两之间差一位即可,这里是其中一种。

The first thing we need to do is to figure out the solution size when given n. we know it is 2^n. Then what we should do is to xor index>>1 and index.

class Solution:    # @return a list of integers    def grayCode(self, n):        size=1<<n        solution=[]        for index in range(size):            solution.append((index>>1)^index)        return solution



0 0
原创粉丝点击