首页 > 其他 > 详细

【LeetCode】89.Gary Code

时间:2016-05-22 06:04:46      阅读:183      评论:0      收藏:0      [点我收藏+]

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)^0000(0)
01(1)^0001(1)
10(2)^0111(3)
11(3)^0110(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 };

 

【LeetCode】89.Gary Code

原文:http://www.cnblogs.com/liez/p/5515999.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!