[letecode java] Gray Code
来源:互联网 发布:飞鸽翻墙软件下载 编辑:程序博客网 时间:2024/06/05 18:15
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
本题让我们求输入n时的格雷码。要是知道格雷码就很简单了,就一个数组更新的问题。如果不知道格雷码,通过观察,我们依然能找到规律。观察n=2和n=1时的格雷码,可以得到以下规律。n=k时的格雷码和n=k-1时的格雷码有关系,n=k的格雷码的前一半刚好是k-1时的格雷码,后一半,最高位变为1,低位的(0、1)排列刚好是k-1时格雷码的倒序。所以只需一个数组,更新时,只更新n=k时的后一半,即可。最后转化为List返回。
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> result=new ArrayList<>();
int[] numbers=new int[(int)Math.pow(2,n)];
numbers[0]=0;
for(int i=1;i<=n;i++){
int length=(int)Math.pow(2,i);
for(int j=(int)Math.pow(2,i-1);j<length;j++){
numbers[j]=numbers[length-1-j]+(1<<(i-1));
}
}
for(int i=0;i<numbers.length;i++){
result.add(numbers[i]);
}
return result;
}
}
- [letecode java] Gray Code
- gray-code Java code
- [Leetcode] Gray Code (Java)
- Gray Code (Java)
- [LeetCode][Java] Gray Code
- leetcode oj java Gray Code
- 【leetcode】89. Gray Code【java】
- [LeetCode] 89. Gray Code java
- [letecode java]Two Sum
- [letecode java] Maximum Subarray
- [letecode java] Unique Paths
- [letecode java ] Sort Colors
- [letecode java] Rotate Image
- [letecode Java] Multiply Strings
- [letecode Java] Decode Ways
- [letecode Java] Triangle
- [letecode Java] Surrounded Regions
- [letecode Java] Word Break
- public class 和 class的区别
- Jmeter压力测试工具
- android布局中更换控件顺序后无法正常运行的解决办法
- 关于多重继承构造函数调用的一点理解与实践
- android混淆和反编译
- [letecode java] Gray Code
- chrome textension Content Security Policy
- linux 下多线程epoll编程 -socket
- C# ListView用法详解
- Maven 3 + Hibernate 3.6 + Oracle 11g Example (Annotation)
- hibernate查询之Criteria实现子查询(GROOVY语法)
- 隐藏自定义的tabBar
- perror打造linux C 编程开发中的错误定位与捕捉函数
- HTML5学习之路(—)