题目:给定一个数字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
原文地址:http://blog.csdn.net/yeweiouyang/article/details/37879233