1. 程式人生 > >gray-code (格雷碼)

gray-code (格雷碼)

itl its where strong str 解題思路 total 編碼 int

題目描述

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.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

什麽是格雷碼?

  格雷碼是一種循環二進制單位距離碼,主要特點是兩個相鄰數的代碼只有一位二進制數不同的編碼,格雷碼的處理主要是位操作 Bit Operation

解題思路:

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

  從左邊第二位起,將每位與左邊一位解碼後的值異或,作為該位解碼後的值。

AC代碼:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector
<int> res; for(int i=0;i<pow(2,n);i++){ res.push_back((i>>1)^i); } return res; } };

gray-code (格雷碼)