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
给定位数n,按顺序输出n位格雷码对应的整数。
思路,格雷码和自然二进制有如下对应关系:
二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0),用计算式表示就是:
G=B^(B>>1)
根据上面的关系式,不难写出程序。
Accepted Solution:
class Solution {
public:
vector<int> grayCode(int n)
{
vector<int> res;
res.resize(1<<n);
int len=res.size();
for(int i=0;i<len;i++)
res[i]=((i>>1)^i);
return res;
}
};