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

题意:这道题要求相邻两个数有且仅有一位不同,并且第一个和最后一个数也满足要求。

思路:好吧,由于本人本科是学通信的,一看到这道题就知道这是大名鼎鼎的格雷编码。其编码规则如下:

整数 二进制 格雷编码

0 000 000

1 001 001

2 010 011

3 011 010

4 100 110

5 101 111

6 110 101

7 111 100

对比格雷码和二进制可知,将二进制的最右边位开始,与其相邻的左一位异或,最左位保持不变,即可得到格雷编码,再将格雷编码转为数字,即满足题目要求。

class Solution {
public:
    vector<int> grayCode(int n) {
        /**************************************
         * 格雷编码
         * **********************************/
         vector<int> aa;
         int bit[32],i,j;
         int result = 0;
         int length = 1;
         while(n--)
         {
             length *= 2;
         }
         for(i=0; i<length; i++)
         {
             result = 0;
             bit[0] = i&1;
             for(j=1; j<32; j++)
             {
                 bit[j] = (i>>j)&1;
                 result += ((bit[j]^bit[j-1]) << (j-1));
             }
             result += (bit[j-1] << (j-1));
             aa.push_back(result);
         }
         return aa;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值