89. Gray Code
来源:互联网 发布:淘宝旺旺号名字大全 编辑:程序博客网 时间:2024/06/03 13:47
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位格雷码集合。n+1位格雷码集合 = n格雷码集合 + (2^n + n位格雷码逆序)集合。如:
n = 2,{00, 01, 11, 10}, n = 3时,格雷码 = {000, 001, 011, 010, 110, 111, 101, 100},后个格雷码是n=2时的格雷码逆序{10, 11, 01, 00}分别在第三个比特位加上1,相当于整体加上2^n-1(当前n=3)。具体定义见百度格雷码。
程序如下:
class Solution { public List<Integer> grayCode(int n) { List<Integer> lst = new ArrayList<>(); if (n == 0){ lst.add(0); return lst; } lst.add(0); lst.add(1); for (int i = 2; i <= n; ++ i){ int len = lst.size(); int val = (int)Math.pow(2, i - 1); for (int j = len - 1; j >= 0; -- j){ lst.add(lst.get(j) + val); } } return lst; }}
- [LeetCode]89.Gray Code
- LeetCode 89. Gray Code
- [Leetcode] 89. Gray Code
- LeetCode --- 89. Gray Code
- [leetcode] 89.Gray Code
- 89. Gray Code
- 89. Gray Code
- 89. Gray Code LeetCode
- 89. Gray Code
- [LeetCode]89. Gray Code
- 89. Gray Code
- 89. Gray Code
- 89. Gray Code
- Leetcode 89. Gray Code
- [leetcode] 89. Gray Code
- 89. Gray Code
- LeetCode *** 89. Gray Code
- 89. Gray Code
- Windows下启动/关闭oracle、执行SQL的bat脚本
- LeetCode题目:44. Wildcard Matching
- localDate的使用
- 【Scikit-Learn 中文文档】线性和二次判别分析
- Moving Pegs UVA
- 89. Gray Code
- 获取DOM元素尺寸及鼠标位置
- 震惊!从未见过如此简单粗暴的Hibernate教程
- Cable master 题解
- 【Scikit-Learn 中文文档】内核岭回归
- 陈国君java第五版第四章课后习题第五题
- JAVA如何使用Redis
- 详解HashMap和HashTable
- 9BRunning Student