Problem:
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:
-
-
-
-
Solution:
理解格雷码和二进制的转换关系这题就很简单了。
格雷码的特点在于相邻两个数字仅有一位不同。题中给出的示例是【00,01,11,10】,原题提示中也说到格雷码的顺序可能不止一种,如【00,10,11,01】亦可,只需满足相邻两数只有一位不同这一条件。
按题示序列规则,对二进制数进行右移运算和异或运算可以得出相应格雷码,如:
// i ^(i>>1)
()^→()
()^→()
()^→()
()^→()
AC Code(C++):
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> seq;
for(int i=;i<(<<n);i++){
seq.push_back(i^(i>>));
}
return seq;
}
};