89. Gray Code

一、题目

  1、审题

  

  2、分析

    给出一个正整数 n ,表示二进制的位数,用 List 存储 n 位二进制表示的所有整数,且相邻的两个数均为只有一个二进制位不同。

二、解答

  1、思路:

    方法一、

      ①、用一个 list 存储整数。初始化时 list 中加入 0;

      ②、循环 n 次,每次循环将 list 中加入 list 中 所有元素的值 加上 1<<i 形成的新元素。

        

public List<Integer> grayCode3(int n) {
        
        List<Integer> resultList = new ArrayList<Integer>();
        resultList.add(0);
        
        for (int i = 0; i < n; i++) {
            int curCount = resultList.size();
            while(curCount != 0) {
                curCount--;
                int curNum = resultList.get(curCount);
                
                curNum += (1 << i);
                resultList.add(curNum);
                // eg、 n = 3
                // 0、1  
                // 1+2=3、0+2=2、
                // 2+4=6、3+4=7、 1+4=5、0+4 = 4
            }
        }
        
        return resultList;
    }

  方法二、

    采用 ^(异或)的方法。。。。

public List<Integer> grayCode(int n) {
    
        List<Integer> resultList = new ArrayList<Integer>();
        
        for(int i = 0; i < 1<<n; i++)     // 1 左移 n 个单位,即 1 * 2^n
            resultList.add(i^ (i >> 1));    // ^: 异或
        // eg、i < 8
        //i = 000、001、010、011、100、101、110、111
        //i/2=000、000、001、001、010、010、011、011
        //      000、001、011、010、110、111、101、100
        return resultList;
    }
原文地址:https://www.cnblogs.com/skillking/p/9703798.html