搜索此博客

2013年2月23日星期六

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.
Solution: we can solve this problem by starting from an example. Assume n=3, we have

000 - 0
001 - 1
011 - 3
010 - 2
110 - 6
111 - 7
101 - 5
100 - 4

The actual sequence of integers is,

000 - 0
001 - 1
010 - 2
011 - 3
100 - 4
101 - 5
110 - 6
111 - 7

By comparing them we find that, the highest bit does not change. Actually, there is a magic to generate the gray code.

http://en.wikipedia.org/wiki/Gray_code

Java语言GrayCode
01 public ArrayList<Integer> grayCode(int n) {
02     ArrayList<Integer> results=new ArrayList<Integer>();
03     int totalNum=1<<n;
04     for(int i=0;i<totalNum;i++)
05     {
06         int number=i^(i>>1);
07         results.add(number);
08     }
09     return results;
10 }

没有评论:

发表评论