【Leetcode】Grey Code
来源:互联网 发布:大数据在银行的应用 编辑:程序博客网 时间:2024/06/05 06:04
【题目】
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 - 001 - 111 - 310 - 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.
【分析】
n = 1
0
1
n=2
0 0
0 1
1 1
1 0
n=3
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0
After growing some rows and cols of the table, you can tell how to build table n+1
from tablen
, namely add 1 to each row of table n
, reverse it and append on table n
. The actual operation is easier since the output only requires a list(not a nested list), so adding bit 1 to a table row is just add 1<<(n-1)
to the number that row represents.
2<<1
2向左移一位
10--》100
2-》4
【代码】
public static ArrayList<Integer> gray(int n){ ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(0); for(int i=0;i<n;i++){ int inc = 1<<i; //n是多少,就有多少位 for(int j=arr.size()-1;j>=0;j--){//倒过来相加 arr.add(arr.get(j)+inc); } } return arr;}
- 【Leetcode】Grey Code
- 089 Grey Code [Leetcode]
- Leetcode练习-Grey Code
- 格雷码生成【grey code】
- leetcode 89. Gray Code 按照index递归解决 + Grey码生成公式
- [Amazon]Given 2 numbers. Find if they are consecutive gray (grey) code sequences
- UIImage图片grey处理
- HDU 4153 Grey Area
- grey world normalization
- UVa 11173 - Grey Codes
- 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
- The Visual Studio Team System “off-road” code coverage experience
- uva10859 Placing Lampposts
- 如何在一个js中引用另一个js的内容
- 如何为文档库里面已经存在的文件修改后缀名
- 批处理管理系统服务
- 【Leetcode】Grey Code
- 【来日复制粘贴】关于排名
- ios调试高德地图api
- 解决ScheduledThreadPoolExecutor关闭连接池方法
- 结合网上的知识,用c++实现了specification模式
- AVL树的查找和插入
- 十年,在我们身边都发生了哪些变化?
- Qt4 SDK(mingw编译版)与VS2008/VS2005的集成开发环境的安装配置
- hadoop伪分布式环境搭建