首页 > 其他 > 详细

[LeetCode]Gray Code

时间:2014-07-18 22:36:30      阅读:399      评论:0      收藏:0      [点我收藏+]

题目:给定一个数字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;
	    }
	}



[LeetCode]Gray Code,布布扣,bubuko.com

[LeetCode]Gray Code

原文:http://blog.csdn.net/yeweiouyang/article/details/37879233

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!