问题描述
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位二进制数的灰码。
灰码的个数一定是 2n 个的,而且一定是全部都有的,所以我们首先声明一个那么大的空间,可以是pow(2, n),也可以直接将1向左移动n位。这道题目也是主要使用了移位的操作的。
然后循环遍历存储结果,将i右移1位然后和它自己异或的结果肯定和自己只有一位是不同的。完美解决问题。
代码
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1<<n);
for (int i = 0; i < (1<<n); i++){
res[i] = i ^ (i>>1);
}
return res;
}
};
时间复杂度:
O(m∗n)
空间复杂度:
O(1)
反思
以下是 C++ ISO 规范 (INCITS/ISO/IEC 14882-2011[2012]) 5.8.2 和 5.8.3 两节中对移位运算符的说明。
E1 << E2
的值是 E1
向左移动 E2
位的结果,空出的位用零填充。 如果 E1 属于无符号类型,则结果的值为 E1 × 2E2
,约减的模一大于结果类型可表示的最大值。 否则,如果 E1
属于有符号类型且为非负值,E1 × 2E2
可由结果类型的相应无符号类型表示,则该值转换为结果类型后即为得到的值;否则,该行为是不确定的。
E1 >> E2
的值是 E1
向右移动 E2
位的结果。 如果 E1
属于无符号类型或 E1
属于有符号类型且为非负值,则结果值为 E1/2E2
之商的整数部分。 如果 E1
属于有符号类型且为负值,则结果值由实现决定。