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,是二进制的位数,任务是从0开始,下一个二进制数与上一个只有其中一位不同,不可重复,将这些二进制数对应的十进制数放入数组,返回这个数据。
PS,顺序不唯一,LeetCode的OJ判断符合要求即可。
举个例子:
00 --> 01 --> 11 --> 10
000 --> 001 --> 011 --> 010 --> 110 --> 111 --> 101 --> 100
不知道众位看官发现规律了没,看n=2的例子,前两个首位不变,变后面那一位,后两个不看首位的1,后面的那位与前两个是对称的。
看n=3的例子的前4个,是n=2的例子在前面加个0而已,后四个与前四个对称,把前面的0换成1。
知道对称有什么用呢?
有大用!
例如n=3的情形,你可以由前两个推后两个,这就有4个了,哈哈哈,由这四个推后四个,搞定!看代码~
1 public ArrayList<Integer> grayCode(int n) { 2 ArrayList<Integer> arrayList = new ArrayList<Integer>(); 3 arrayList.add(0); 4 for (int i = 0; i < n; i++) { 5 int xchg = 1 << i; 6 int j = arrayList.size() - 1; 7 do { 8 int next = arrayList.get(j) + xchg; 9 arrayList.add(next); 10 } while (j-- > 0); 11 } 12 return arrayList; 13 }