[轉載]LeetCode: 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

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.

二進制碼->格雷碼(編碼):從最右邊一位起,依次將每一位與左邊一位異或(XOR),作爲對應格雷碼該位的值,最左邊一位不變(相當於左邊是0);
格雷碼->二進制碼(解碼):從左邊第二位起,將每位與左邊一位解碼後的值異或,作爲該位解碼後的值(最左邊一位依然不變)。

Gray Code 0 = 0, 下一項是toggle最右邊的bit(LSB), 再下一項是toggle最右邊值爲 “1” bit的左邊一個bit,然後重複。直到最右邊值爲 “1” 的bit在最左邊了,結束。

  1. class Solution {  
  2. public:  
  3.     vector<int> grayCode(int n) {  
  4.         // Start typing your C/C++ solution below  
  5.         // DO NOT write int main() function  
  6.         vector<int> result;  
  7.         int nSize = 1 << n;  
  8.         for (int i = 0; i < nSize; ++i)  
  9.         {  
  10.             result.push_back((i>>1)^i);  
  11.         }  
  12.         return result;  
  13.     }  
  14. }; 

轉載於:https://www.cnblogs.com/ericsun/p/3320429.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章