標籤:數學公式 轉換 ble i+1 out gray code [] void uniq
描述
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.
分析
格雷碼 (Gray Code) 的定義請參考 wikipedia http://en.wikipedia.org/wiki/Gray_code。
自然二進位碼轉換為格雷碼:g0 = b0, gi = bi ⊕ bi?1
保留自然二進位碼的最高位作為格雷碼的最高位,格雷碼次高位為二進位碼的高位與次高位異
或,其餘各位與次高位的求法類似。例如,將自然二進位碼 1001,轉換為格雷碼的過程是:保留最
高位;然後將第 1 位的 1 和第 2 位的 0 異或,得到 1,作為格雷碼的第 2 位;將第 2 位的 0 和第 3 位
的 0 異或,得到 0,作為格雷碼的第 3 位;將第 3 位的 0 和第 4 位的 1 異或,得到 1,作為格雷碼的
第 4 位,最終,格雷碼為 1101。
格雷碼轉換為自然二進位碼:b0 = g0, bi = gi ⊕ bi?1
保留格雷碼的最高位作為自然二進位碼的最高位,次高位為自然二進位高位與格雷碼次高位異
或,其餘各位與次高位的求法類似。例如,將格雷碼 1000 轉換為自然二進位碼的過程是:保留最高
位 1,作為自然二進位碼的最高位;然後將自然二進位碼的第 1 位 1 和格雷碼的第 2 位 0 異或,得到
1,作為自然二進位碼的第 2 位;將自然二進位碼的第 2 位 1 和格雷碼的第 3 位 0 異或,得到 1,作
為自然二進位碼的第 3 位;將自然二進位碼的第 3 位 1 和格雷碼的第 4 位 0 異或,得到 1,作為自然
二進位碼的第 4 位,最終,自然二進位碼為 1111。
格雷碼有數學公式,整數 n 的格雷碼是 n ⊕ (n/2)。
這題要求產生 n 位元的所有格雷碼。
最簡單的方法,利用數學公式,對從 0 ~ 2
n ? 1 的所有整數,轉化為格雷碼。
n 位元的格雷碼,可以遞迴地從 n ? 1 位元的格雷碼產生。
這題我折騰了很久,勉強的通過了。但偶爾看到有更簡潔的方法(@愛做飯的小瑩子),在建數組時用了遞迴。為方便自己學習,所以也貼上來。
代碼:
1 import java.util.ArrayList; 2 3 public class Graycode { 4 5 public static void main(String[] args) { 6 int n=3; 7 System.out.println(grayCode(n)); 8 } 9 public static ArrayList<Integer> grayCode(int n) { 10 if(n==0) { 11 ArrayList<Integer> result = new ArrayList<Integer>(); 12 result.add(0); 13 return result; 14 } 15 16 ArrayList<Integer> result = grayCode(n-1);17 // ArrayList<Integer> result = new ArrayList<Integer>(n);18 int addNumber = 1 << (n-1);19 int asize=result.size();20 21 for(int i=asize-1;i>=0;i--) { 22 result.add(addNumber + result.get(i)); 23 } 24 return result; 25 }26 }
然後,我有看到了更簡單的方法。格雷碼,二進位轉格雷碼的方法是將二進位前補0,然後前後兩位異或。gi = bi ^ bi+1 比如 二進位 0101, 則前面添0後 00101,
然後從右向左兩兩位異或得0111 (相異為1,相同為0),得到格雷碼 0111, 其實就是對二進位x做 (x>>1)^x 操作。
1 public class Solution { 2 public List grayCode(int n) { 3 List list = new ArrayList(); 4 if(n<0) { 5 return list; 6 } 7 for(int i=0; i< (1<<n); i++) { 8 list.add((i>>1)^i); 9 }10 return list;11 }12 }
Gray Code LeetCode Java