89. Gray Code

来源:互联网 发布:太阳社玻尿酸原液 知乎 编辑:程序博客网 时间:2024/05/22 01:32

Problem:

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 - 001 - 111 - 310 - 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表示一个二进制的位数,然后输出所有二进制对应的格雷码所对应的十进制值。而且这里讨论的是比较自然的格雷码的排序。也就是从十进制的顺序。格雷码的定义:

https://baike.baidu.com/item/%E6%A0%BC%E9%9B%B7%E7%A0%81

题意是很简单,但是做法我觉得不是很好想,效率不是很高,因为根据格雷码的定义,需要两两异或,所以时间肯定是O(2^n)级别的。

然后我去查找了一下,发现了一个关于格雷码的数学公式:G(n) = n xor (n/2),所以代码如下:


Code:(LeetCode运行6ms)

class Solution {public:    vector<int> grayCode(int n) {        //2^n种gray码        int size = 1 << n;        vector<int> result;        for (int i = 0; i < size; i++) {            result.push_back(IntToGray(i));        }        return result;    }    int IntToGray(int i) {        return i ^ (i >> 1);    }};


原创粉丝点击