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.
题目的意思是按照格雷码的顺序输出对应的n内的十进制数值数组。按照十进制的顺序对应的二进制值转换成格雷码之后正好是连续的,每个二进制值转换成格雷码的方法是最高位不变,其他各位为当前位与前一位的异或值,因此可以用数学公式n^(n>>1)来转换,一共有2的n次方个数,可以用1<<n位来得到。
class Solution {
public:
int togray(int a)
{
return a^(a>>1);
}
vector<int> grayCode(int n) {
//按照二进制的顺序0,1,2,3转换成格雷码正好是连续的,二进制转换成格雷码的公式为最高位不变,其他各位为当前位与前一位的异或值,因此可以用数学公式n^(n>>1)来转换,一共有2的n次方个数,可以用1<<n位来得到
vector<int> result;
for(int i=0;i<(1<<n);i++)
{
result.push_back(togray(i));
}
return result;
}
};