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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM