思路:
考察二进制到格雷码的转换。
方法一:数学公式。
gray_code = binary_code ^ (binary_code>>1);
class Solution {
private:
int binary2gray(int n) {
return n ^ (n>>1);
}
public:
vector<int> grayCode(int n) {
vector<int> ans;
const int size = 1<<n;
ans.reserve(size);
for(int i = 0; i < size; ++i) {
ans.push_back(binary2gray(i));
}
return ans;
}
};
方法二: