LeetCode: Gray Code 解题报告

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.

SOLUTION 1:

我们可以使用递归来做。规律是:

一部分是n-1位格雷码,再加上 1<<(n-1)和n-1位格雷码的逆序的和。

具体可以看维基的解释: http://zh.wikipedia.org/wiki/格雷码

格雷碼能避免訊號傳送錯誤的原理
傳統的二進位系統例如數字3的表示法為011,要切換為鄰近的數字4,也就是100時,裝置中的三個位元都得要轉換,因此於未完全轉換的過程時裝置會經歷短暫的,010,001,101,110,111等其中數種狀態,也就是代表著2、1、5、6、7,因此此種數字編碼方法於鄰近數字轉換時有比較大的誤差可能範圍。葛雷碼的發明即是用來將誤差之可能性縮減至最小,編碼的方式定義為每個鄰近數字都只相差一個位元,因此也稱為最小差異碼,可以使裝置做數字步進時只更動最少的位元數以提高穩定性。 數字0~7的編碼比較如下:

十進位 葛雷碼 二進位

0     000    000
1     001    001
2     011    010
3     010    011
4     110    100
5     111    101
6     101    110
7     100    111

 1 public class Solution {
 2     public List<Integer> grayCode(int n) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         if (n == 0) {
 5             ret.add(0);
 6             return ret;
 7         }
 8         
 9         ret = grayCode(n - 1);
10         
11         for (int i = ret.size() - 1; i >= 0; i--) {
12             int num = ret.get(i);
13             num += 1 << (n - 1);
14             ret.add(num);
15         }
16         
17         return ret;
18     }
19 }

 

JAVA 运算符优先级:

需要注意的是 << 的优先级 还不如+,所以,运算时,要记得加括号:

ret.add(ret.get(i) + (1 << (n - 1)));

在实际的开发中,可能在一个运算符中出现多个运算符,那么计算时,就按照优先级级别的高低进行计算,级别高的运算符先运算,级别低的运算符后计算,具体运算符的优先级见下表:

 
运算符优先级表

优先级 运算符 结合性
1 () [] . 从左到右
2 ! +(正)  -(负) ~ ++ -- 从右向左
3 * / % 从左向右
4 +(加) -(减) 从左向右
5 << >> >>> 从左向右
6 < <= > >= instanceof 从左向右
7 ==   != 从左向右
8 &(按位与) 从左向右
9 ^ 从左向右
10 | 从左向右
11 && 从左向右
12 || 从左向右
13 ?: 从右向左
14 = += -= *= /= %= &= |= ^=  ~=  <<= >>=   >>>= 从右向左
 
   说明:
 
  1、 该表中优先级按照从高到低的顺序书写,也就是优先级为1的优先级最高,优先级14的优先级最低。
 
  2、 结合性是指运算符结合的顺序,通常都是从左到右。从右向左的运算符最典型的就是负号,例如3+-4,则意义为3加-4,符号首先和运算符右侧的内容结合。
 
  3、 instanceof作用是判断对象是否为某个类或接口类型,后续有详细介绍。
 
  4、 注意区分正负号和加减号,以及按位与和逻辑与的区别
 
  其实在实际的开发中,不需要去记忆运算符的优先级别,也不要刻意的使用运算符的优先级别,对于不清楚优先级的地方使用小括号去进行替代,示例代码:
         int m = 12;
         int n = m << 1 + 2;
         int n = m << (1 + 2); //这样更直观
 
这样书写代码,更方便编写代码,也便于代码的阅读和维护。

http://blog.csdn.net/xiaoli_feng/article/details/4567184

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/recursion/GrayCode.java

 

REF:

http://blog.csdn.net/fightforyourdream/article/details/14517973

 

posted on 2014-11-25 19:53  Yu's Garden  阅读(2202)  评论(1编辑  收藏  举报

导航