本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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.

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

分析:关于格雷码请参考wiki百度百科

二进制转格雷码:gray = (binary) xor (binary >> 1)

代码如下:

 1 class Solution {
 2 public:
 3     vector<int> grayCode(int n) {
 4         //注意n = 0时,输出{0}而不是空数组
 5         int num = 1<<n;
 6         vector<int> res;
 7         res.reserve(num);
 8         for(int i = 0; i < num; i++)
 9             res.push_back(i^(i>>1));
10         return res;
11     }
12 };

 

这篇文章有一个对格雷码很有意思的解释

顺便科普一下解码(格雷码 转 二进制码)方法(摘自百度百科):

格雷码→二进制码(解码):
从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。依次异或,直到最低位。依次异或转换后的值(二进制数)就是格雷码转换后二进制码的值。
公式表示:
(G:格雷码,B:二进制码)
原码:p[n:0];格雷码:c[n:0](n∈N);编码:c=G(p);解码:p=F(c);
书写时按从左向右标号依次减小,即MSB->LSB,编解码也按此顺序进行
举例:
如果采集器器采到了格雷码:1010
就要将它变为自然二进制:
0 与第四位 1 进行异或结果为 1
上面结果1与第三位0异或结果为 1
上面结果1与第二位1异或结果为 0
上面结果0与第一位0异或结果为 0
因此最终结果为:1100 这就是二进制码即十进制 12
当然人看时只需对照表1一下子就知道是12

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3451938.html

posted @ 2013-11-30 23:37  tenos  阅读(2488)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童