码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Gray Code

时间:2015-03-06 15:34:13      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

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

这个题目很搞笑的,因为记得格雷码和二进制码之间是有转换关系的,所以可以直接通过这个关系来做这个题目。下面是转换关系:
  二进制数转格雷码
  格雷码第n位 = 二进制码第(n+1)位+二进制码第n位。不必理会进制。
     代码:gray=(binary>>1)^(异或)binary
  格雷码转二进制数
  二进制码第n位 = 二进制码第(n+1)位+格雷码第n位。因为二进制码和格雷码皆有相同位数,所以二进制码可从最高位的左边位元取0,以进行计算。
      for(i=0;i<=n-1;i=i+1)
              binary[i]= ^(gray>>i)//gray移位后,自身按位异或
方案一、直接按照上面的转换规则来
  代码:
class Solution:
    # @return a list of integers
    def grayCode(self, n):
        res = []
        for i in range(1<<n):
            gray = i ^ i>>1
            res.append(gray)
        return res

 

方案二、找规律
    初始化2n位0,改变最低位,然后改变最右边的‘1’的左一位,重复执行,直到结束。
方案三、回溯
    通过回溯法,也是网站提示的方法,这里我没研究过,这题算是水过了的!

【leetcode】Gray Code

标签:

原文地址:http://www.cnblogs.com/KingKou/p/4318055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!