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 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode; | |
import java.util.ArrayList; | |
/** | |
* Solution: GrayCode(n=k), is equals to GrayCode(n = k-1) reverse + 1<<k. Calculate Layer by Layer. | |
* The gray code -- two successive values differ in only one bit. But there's many combinations for a n > 2. | |
* | |
* 0 00 0 | |
* 0 01 1 | |
* 0 11 3 | |
* 0 10 2 | |
* ---- | |
* 1 10 2 + 4 | |
* 1 11 3 + 4 | |
* 1 01 1 + 4 | |
* 1 00 0 + 4 | |
* | |
* Reference: http://fisherlei.blogspot.com/2012/12/leetcode-gray-code.html | |
* | |
* @author jeffwan | |
* @date Apr 4, 2014 | |
*/ | |
public class GrayCode { | |
public ArrayList<Integer> grayCode(int n) { | |
ArrayList<Integer> result = new ArrayList<Integer>(); | |
if (n < 0) { | |
return result; | |
} | |
result.add(0); | |
for (int i = 0; i < n; i++) { | |
int highestBit = 1 << i; | |
int length = result.size(); | |
for (int j = length - 1; j >= 0; j--) { | |
result.add(highestBit + result.get(j)); | |
} | |
} | |
return result; | |
} | |
// Mathematical Solution: i --> (i>>1)^i No meaning in interview. | |
public ArrayList<Integer> grayCode2(int n) { | |
ArrayList<Integer> result = new ArrayList<Integer>(); | |
if (n < 0) { | |
return result; | |
} | |
int size = 1 << n; | |
for (int i = 0; i < size; i++) { | |
result.add((i >> 1) ^ i); | |
} | |
return result; | |
} | |
} |
No comments:
Post a Comment