Gray Code

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.

Solution and Precautions:

Well, if you have ever learned about Gray code, it is actually known as reflected binary code, the name shows how this kind of code is constructed:  In a recursive way, gray code with n bits could be constructed from the gray code with n-1 bits.

(1) prefix all the gray code with n-1 bits with 0

(2) reverse the order of the n-1 bit gray code and prefix all of them with 1 (reflected)

(3) concatenate (1) and (2) to get the gray code of n bits

Gray Code is recursive.

2位元格雷码
00
01
11
10
3位元格雷码
000
001
011
010
110
111
101
100 
4位元格雷码
0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
 1 public class Solution {
 2     public ArrayList<Integer> grayCode(int n) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<Integer> result = new ArrayList<Integer>();
 6         result.add(0);
 7         if(n == 0) return result;
 8         result.add(1);
 9         if(n == 1) return result;
10         for(int i = 1; i < n; i ++){
11             for(int j = result.size() - 1; j > -1; j--){
12                 result.add((int)Math.pow(2, i) + result.get(j));
13             }
14         }
15         return result;
16     }
17 }

 Solution:

这一题分析清楚之后很简单, 主要就是gray code的生成顺序。他都说基于原来的代码进行扩充的,只是注意在扩充的时候需要反序(mirror),然后再乘上2的乘方即可。

posted on 2013-09-26 06:58  Step-BY-Step  阅读(250)  评论(0编辑  收藏  举报

导航