zoukankan      html  css  js  c++  java
  • Java for LeetCode 089 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.

    解题思路:

    格雷码,学过通信原理的童鞋应该都不陌生,只不过格雷码的生成方法不是按照题目中描述的那样,下面科普下格雷码的生成方法:

    n=1 得到0 1

    n=2 得到00 01 11 10(注意,11 和 10除了符号位外,和 00 01对称的)

    n=3 得到000 001 011 010 110 111 101 100(后面四位除了符号位之外,和前四位对称)

    n=4 依次类推

    知道了格雷码的生成过程,那么JAVA实现如下:

       static public List<Integer> grayCode(int n) {
            List<Integer> list=new ArrayList<Integer>();
            for(int i=0;i<Math.pow(2, n);i++){
            	int result=0,num=i,temp=n;
            	while(temp>1){
            		if(num>=Math.pow(2, temp-1)){
            			num=(int) (2*Math.pow(2, temp-1)-num-1);
            			result+=Math.pow(2, temp-1);
            		}
            		temp--;
            	}
            	result+=num;
            	list.add(result);
            }
            return list;
        }
    

     同时,本题有一个非常简洁的写法,如下:

        public List<Integer> grayCode(int n) {
            List<Integer> res = new ArrayList<Integer>();
            for (int i = 0; i < (1<<n); ++i)
                res.add(i ^ (i>>1));
            return res;
        }
    
  • 相关阅读:
    Elasticsearch与kibana的单机安装
    PS 设计带斑点图案的背景
    中国传统纹样简略
    js 在非module中引用module里的变量和函数
    ssh 使用pem秘钥文件登录
    jquery sortable 使用注意事项
    ES6中的函数、对象定义
    file-loader返回object Module 路径的问题
    Louvain 论文笔记
    基于Docker方式的LNMP环境搭建
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4516080.html
Copyright © 2011-2022 走看看