您的位置:首页 > 其它

[LeetCode] Gray Code

2013-10-24 13:30 239 查看
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

问题描述:gray code是一种二进制数字系统,在这个系统中,两个相邻的数字之间只有一位不同。
给定一个非负整数n,n表示总共的位数,请打印出该gray code的序列,该序列必须以0开始。
后面给了一个n为2时的例子,如果要是能够利用这个例子来构造n值的序列就好了。通过分析可以得出,n的序列可以通过n-1的序列构造,将n-1的序列反向添加到原来的序列后面,
再原来的序列前加0,后来的序列前加1,其实也可以在后面加,但是OJ采用的是在前面加。
class Solution {
public:
vector<int> grayCode(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> vec;

if(n == 0) {
vec.push_back(0);
return vec;
}

vec = grayCode(n-1);

int i = 0;
for(i = vec.size()-1; i >= 0; i--) {
vec.push_back(vec.at(i) | (1<<(n-1)));
}

return vec;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode graycode