Gray Code, Leetcode 解题笔记

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.

很无聊的找规律题,感觉除了练习一下bit操作,对面试并没什么帮助。
以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
可以看到第n位的格雷码由两部分构成,一部分是n-1位格雷码,再加上 1<<(n-1)和n-1位格雷码的逆序的和。

public class Solution {
    public ArrayList&lt;Integer&gt; grayCode(int n) {
        if(n==0) {
            ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;();
            result.add(0);
            return result;
        }
        
        ArrayList&lt;Integer&gt; tmp = grayCode(n-1);
        int addNumber = 1 &lt;&lt; (n-1);
        ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(tmp);
        for(int i=tmp.size()-1;i&gt;=0;i--) {
            result.add(addNumber + tmp.get(i));
        }
        return result;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s