[LeetCode]Gray Code

题目:给定一个数字n,表示二进制数字的位数,求出n位格雷码相应的十进制数

比如,给定n=2,则返回 [0,1,3,2]. 它的格雷码序列是:

00 - 0
01 - 1
11 - 3
10 - 2
算法:

二进制	二进制右移	格雷码
--------------------------
000		000			000
001		000			001
010		001			011
011		001			010
100		010			110
101		010			110
110		011			101
111		011			100
 
得出 : garyCode = x ^ (x>>1)
public class Solution {
		/**
		 * Algorithm:
		 * 
		 * binary	binary>>1	gray
		 * --------------------------
		 * 000		000			000
		 * 001		000			001
		 * 010		001			011
		 * 011		001			010
		 * 100		010			110
		 * 101		010			110
		 * 110		011			101
		 * 111		011			100
		 * 
		 * find : garyCode = x ^ (x>>1)
		 * 
		 */
	    public List<Integer> grayCode(int n) {
	        List<Integer> grayCodeList = new ArrayList<Integer>();
	    	
	    	int nLoops = (1 << n);  // 2^n-1
	    	for (int i=0; i<nLoops; ++i) {
	    		int grayCode = (i ^ (i >> 1));
	    		
	    		grayCodeList.add(grayCode);
	    	}
	    	return grayCodeList;
	    }
	}



原文地址:https://www.cnblogs.com/tlnshuju/p/6745224.html