leetcode------Gray Code

标题: Gray Code
通过率: 32.4%
难度: 中等

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.

本题总体还是比较简单,就是在不知道什么是格雷码的情况下还是比较难做的,下面我贴出二进制转格雷码的实例:

按照此方法写代码,一目了然,主要就是源码前面补0的问题,然后就是如何把格雷码转换回来,如下公式:

公式表示

(G:格雷码,B:二进制码)

java代码如下:

 1 public class Solution {
 2     public List<Integer> grayCode(int n) {
 3         List<Integer> result=new ArrayList<Integer>();
 4         String temp,gray;
 5         if(n==0){
 6             result.add(0);
 7             return result;
 8         }
 9         for(int i=0;i<Math.pow(2,n);i++){
10             temp=Integer.toBinaryString(i);
11             temp=putEquelLen(n,temp);
12             gray="";
13             for(int j=0;j<n;j++){
14                 int t=Integer.valueOf(temp.charAt(j))^Integer.valueOf(temp.charAt(j+1));
15                 gray+=t;
16             }
17             result.add(Integer.valueOf(gray,2));
18         }
19         return result;
20         
21     }
22     public String putEquelLen(int n,String str){
23        int len=str.length();
24         len=n-len+1;
25         for(int i=0;i<len;i++){
26             str="0"+str;
27         }
28         return str;
29     }
30 }

在网上发现其实就相当于一个数 (x>>1)^x的操作;

下面贴出python代码:

 1 class Solution:
 2     # @return a list of integers
 3 
 4     def grayCode(self, n):
 5         if n <= 0:
 6             return [0]
 7         ret = [0, 1]
 8         if n == 1:
 9             return ret
10 
11         for x in xrange(1, n):
12             old = list(ret)
13             new = old[::-1]
14             for (i, a) in enumerate(new):
15                 new[i] = a + (1 << x)
16             ret = old + new
17 
18         return ret
原文地址:https://www.cnblogs.com/pkuYang/p/4277358.html