89. 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
分析
格雷码序列生成问题,序列中前后连续的两个数的二进制只有一位比特位不同,用下面这张图表示:

格雷码有个公式,自然整数n
对应的格雷码为:
n ^ (n/2)
源码
class Solution {
public:
// 格雷码数学公式:整数n的格雷码为: n^(n >> 1)
// 现在要生成所有n比特的格雷码
vector<int> grayCode(int n) {
vector<int> ret;
size_t size = 1 << n ;//2^n个自然数
for(size_t i = 0; i < size; i++){
ret.push_back(i ^ (i >> 1));
}
return ret;
}
};