[LeetCode]Gray Code

来源:互联网 发布:杭州 夜场小姐数据 编辑:程序博客网 时间:2024/06/10 20:52

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

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

00 - 001 - 111 - 310 - 2
算法:

二进制二进制右移格雷码--------------------------000000000001000001010001011011001010100010110101010110110011101111011100 得出 : garyCode = x ^ (x>>1)
public class Solution {/** * Algorithm: *  * binarybinary>>1gray * -------------------------- * 000000000 * 001000001 * 010001011 * 011001010 * 100010110 * 101010110 * 110011101 * 111011100 *  * 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;    }}



2 0
原创粉丝点击