Java for LeetCode 089 Gray Code
2015-05-20 00:52
441 查看
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
Note:
For a given n, a gray code sequence is not uniquely defined.
For example,
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 得到00 01 11 10(注意,11 和 10除了符号位外,和 00 01对称的)
n=3 得到000 001 011 010 110 111 101 100(后面四位除了符号位之外,和前四位对称)
n=4 依次类推
知道了格雷码的生成过程,那么JAVA实现如下:
同时,本题有一个非常简洁的写法,如下:
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.
解题思路:
格雷码,学过通信原理的童鞋应该都不陌生,只不过格雷码的生成方法不是按照题目中描述的那样,下面科普下格雷码的生成方法:
n=1 得到0 1
n=2 得到00 01 11 10(注意,11 和 10除了符号位外,和 00 01对称的)
n=3 得到000 001 011 010 110 111 101 100(后面四位除了符号位之外,和前四位对称)
n=4 依次类推
知道了格雷码的生成过程,那么JAVA实现如下:
static public List<Integer> grayCode(int n) { List<Integer> list=new ArrayList<Integer>(); for(int i=0;i<Math.pow(2, n);i++){ int result=0,num=i,temp=n; while(temp>1){ if(num>=Math.pow(2, temp-1)){ num=(int) (2*Math.pow(2, temp-1)-num-1); result+=Math.pow(2, temp-1); } temp--; } result+=num; list.add(result); } return list; }
同时,本题有一个非常简洁的写法,如下:
public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < (1<<n); ++i) res.add(i ^ (i>>1)); return res; }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【089-Gray Code(格雷码)】
- Java for LeetCode 094 Binary Tree Inorder Traversal
- Java for LeetCode 134 Gas Station
- LeetCode 89(Gray Code)java
- leetcode 34. Search for a Range | Java最短代码实现
- Java for LeetCode 137 Single Number II
- Java for LeetCode 222 Count Complete Tree Nodes
- LeetCode : Search for a Range [java]
- Java for LeetCode 145 Binary Tree Postorder Traversal
- Java for LeetCode 109 Convert Sorted List to Binary Search Tree
- (Java)LeetCode-34. Search for a Range
- Java for LeetCode 150 Evaluate Reverse Polish Notation
- Java for LeetCode 120 Triangle
- Java for LeetCode 172 Factorial Trailing Zeroes
- Java for LeetCode 047 Permutations II
- Java for LeetCode 049 Anagrams
- Java for LeetCode 207 Course Schedule【Medium】
- Java for LeetCode 124 Binary Tree Maximum Path Sum
- Java for LeetCode 057 Insert Interval
- Java for LeetCode 126 Word Ladder II 【HARD】