Leetcode: Gray Code
来源:互联网 发布:js 手写板插件 编辑:程序博客网 时间:2024/06/04 20:03
Question
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
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.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
Show Tags
Have you met this question in a real interview? Yes No
Discuss
Solution 1
Get idea from here1, here2
class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ if n==0: return [0] res = [] temp = self.grayCode(n-1) high = 1<<(n-1) result = temp[:] for ind in range(len(result)-1,-1,-1): result.append( high+temp[ind] ) return result
Solution 2
class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ if n==0: return [0] res = [] num = 1<<n for ind in range(num): res.append((ind>>1)^ind) return res
- LeetCode: Gray Code
- [LeetCode] 格雷码(Gray Code)
- LeetCode Gray Code
- [Leetcode] Gray Code
- [LeetCode] Gray Code
- leetcode 112: Gray Code
- LeetCode Gray Code
- [leetCode] Gray Code
- [LeetCode]Gray Code
- Leetcode: Gray Code
- [leetcode]Gray Code
- LeetCode-Gray Code
- [leetcode] Gray Code
- LeetCode - Gray Code
- leetcode之Gray code
- LeetCode:Gray Code
- 【转载】【leetcode】Gray Code
- LeetCode - Gray Code
- 第十二章 动态内存
- cygwin下面编译proxmark3(at 2015.09.09)
- Hibernate基于Spring模板的DAO基类
- 欢迎使用CSDN-markdown编辑器
- JSON和Java实体之间的数据类型映射
- Leetcode: Gray Code
- 自绘button
- python语法检查利器pychecker
- 初窥Linux 之 ext2/ext3文件系统
- 网络IO模型
- Mysql中in和find_in_set的使用说明
- Fresco 最全最简单的Fresco 可以导入Eclipse FrescoDemo并且直接可以运行
- Processing 练习(7)- 抽象空间_欣赏_000
- arcgis对sqlite数据库的支持情况