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