zoukankan      html  css  js  c++  java
  • [leedcode 89] Gray Code

    The gray code is a binary numeral system where two successive values differ in only one bit.

    Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

    For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

    00 - 0
    01 - 1
    11 - 3
    10 - 2
    

    Note:
    For a given n, a gray code sequence is not uniquely defined.

    For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

    For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

    public class Solution {
        public List<Integer> grayCode(int n) {
           //自然数(二进制表示)转化为格雷码的公式是:i>>1^i
           //例如:Binary Code :1011 要转换成Gray Code 
           //(1011 >> 1)^1011 = 1110
            int size=1<<n;//先求出二进制一共的个数
            List<Integer> res=new ArrayList<Integer>();
            for(int i=0;i<size;i++){
                res.add(i>>1^i);
            }
            return res;
        }
            /*格雷码的规律是 将格雷码看成是上下两部分 n=1 
    
            上 0  下 1
    
            当n=2
    
            上为n=1时的格雷码 
    
            下为n=1时的格雷码的倒序再加上最前面的1*/
    }
  • 相关阅读:
    链表的相关操作
    【回溯】旅行商问题
    【回溯】图的m着色问题
    奶牛卧室_待解决
    阶乘问题
    子数整数
    hihoCoder week4 Trie图
    hihoCoder week3 KMP算法
    hihoCoder week2 Trie树
    hihoCoder week1 最长回文子串
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4650875.html
Copyright © 2011-2022 走看看