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*/
    }
  • 相关阅读:
    解决“Kali Linux终端打不开”
    国内网站备案。备案的是域名?还是服务器?
    Linux磁盘分区
    Linux各目录的作用
    vim基础操作
    基础算法-->堆排序
    期望,方差,标准差,正态分布
    平面向量
    基础算法 ---> 二分法
    学习人工智能准备了解的算法
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4650875.html
Copyright © 2011-2022 走看看