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 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=1----n=4的格雷码,开始找规律。
2 发现不管n等于几,开头总是一样的;n越大,后面增加的数字越多。
3 发觉每次n后半部分的数字都是前半部分数字倒序后+固定数量的数,这个数是2^n-1,通过观察二进制也能够发现规律。
4 从0到1到2都是如此,所以这是普遍现象,可以完美使用循环。
ps 看到另外一种方法,前提是知道格雷码的计算特点
http://blog.youkuaiyun.com/fightforyourdream/article/details/14517973
public class Solution {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> ans = new ArrayList<Integer>();
if(n<0){
return ans;
}
ans.add(0);
int s =0;
while(s<n){
int maxs = 1<<s;
for(int i=ans.size()-1;i>=0;i--){
int temp = ans.get(i);
ans.add(temp+maxs);
}
s++;
}
return ans;
}
}