Gray Code

时间:2022-03-08 09:02:37
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.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

以上是题目。想的时候要先把问题减少到最小规模,也就是1位。然后再扩展成两位,再扩展成3位,从而发现当位数增加时低位的变化规律。把问题简化到最小规模,且不改变问题本质的方法非常适用于解决实际问题。

这题的数字变化规律是: 每向高位增加一位,则所有低位的二进制按照从下到上的逆序复制一遍就行了。比如例子中的3,看成是最高位的1和3上一个数字对应3的低位部分的复制(复制的是1的位)。4就是最高位的1加上复制的0的位。写成代码如下:

vector<int> grayCode(int n) {
vector<int> res;
res.push_back(0);
if (n > 0)
res.push_back(1); int cnt = 2;
for (int k = 1; k < n; k++)
{
int preBitsNum = std::pow(2, k);
/*if (preBitsNum == 1)
preBitsNum = 0;*/
for (int i = 0; i < preBitsNum; i++)
{
int cur = 1 << k;
cur |= res[cnt++ - i * 2 - 1];
res.push_back(cur);
}
}
return res;
}