89. 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.

思路: 格雷码问题,刚开始真是没整明白,关于grey code wiki的解释, 这个题是给定n,求对应的格雷码序列,注意这里格雷码序列跟二进制计数还是有所不同的,格雷码序列中前后两个数的二进制位只有一个比特位是不同的。 对应n也有个公式:n^(n / 2)或者写作n^(n >> 1)

public class Solution {
    public List<Integer> grayCode(int n) {
        //格雷码数学公式:整数n的格雷码为: n^(n >> 1) 
        List<Integer> res = new ArrayList<Integer>();
        if (n < 0) return res;
        int size = 1 << n;
        for (int i = 0; i < size; i++) {
            res.add(i ^ (i >> 1));
        }
        return res;
    }
}
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