博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
89. Gray Code
阅读量:7120 次
发布时间:2019-06-28

本文共 1355 字,大约阅读时间需要 4 分钟。

一、题目

  1、审题

  

  2、分析

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

 

二、解答

  1、思路:

    方法一、

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

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

        

public List
grayCode3(int n) { List
resultList = new ArrayList
(); 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
grayCode(int n) { List
resultList = new ArrayList
(); for(int i = 0; i < 1<
> 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

你可能感兴趣的文章
每天一个linux命令(23):Linux 目录结构
查看>>
数据库Sharding的基本思想和切分策略
查看>>
我的友情链接
查看>>
【极客学院出品】Cocos2d-X系列课程之六-用户交互事件处理方法
查看>>
JSP include directive 和JSP include的区别
查看>>
【2】puppet笔记 - package、service、user资源
查看>>
Cinder - 云硬盘加密
查看>>
Centos7下,LVM根分区扩容
查看>>
centos安装redmine项目管理系统
查看>>
java返回ajax的请求值
查看>>
lamp编译安装
查看>>
用gcc/g++编译运行C/C++程序
查看>>
mysql利用init-connect增加访问审计功能的实现
查看>>
Ubuntu 10.04下更行新内核
查看>>
数据恢复工程师视角看腾讯云静默损坏事件
查看>>
Mybitis框架2016年1月3日
查看>>
AT&T全球网络运营中心GNOC
查看>>
FPI厂商SoleraNetworks被Blue Coat收购
查看>>
myeclipse安装svn插件的多种方式
查看>>
Hadoop学习曲线图
查看>>