【题目】
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 = 1
0
1
n=2
0 0
0 1
1 1
1 0
n=3
0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 1 1
1 0 1
1 0 0
After growing some rows and cols of the table, you can tell how to build table n+1
from
tablen
, namely add 1 to each row of table n
,
reverse it and append on table n
. The actual operation is easier since the output
only requires a list(not a nested list), so adding bit 1 to a table row is just add 1<<(n-1)
to
the number that row represents.
2<<1
2向左移一位
10--》100
2-》4
【代码】
public static ArrayList<Integer> gray(int n){
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(0);
for(int i=0;i<n;i++){
int inc = 1<<i; //n是多少,就有多少位
for(int j=arr.size()-1;j>=0;j--){//倒过来相加
arr.add(arr.get(j)+inc);
}
}
return arr;}