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

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

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 - 001 - 111 - 310 - 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.

 

 解法1 dp+非位运算

  规律:

public class Solution {    public List
grayCode(int n) { if(n == 0) { List
l1 = new ArrayList<>(); l1.add(0); return l1; } List
> list = new ArrayList<>(); List
l1 = new ArrayList<>(); List
res = new ArrayList<>(); l1.add("0"); l1.add("1"); list.add(l1); for(int i = 1 ; i < n ; i++){ List
member = list.get(i-1); List
next = new ArrayList<>(); for(String s : member){ String newS = "0"+ s; next.add(newS); } for(int j = member.size() -1 ; j >= 0; j--){ String newS = "1"+ member.get(j); next.add(newS); } list.add(next); } List
l = list.get(n-1); for(String str : l){ res.add(getValueofBit(str)); } return res; } public int getValueofBit(String s){ int res = 0; for(int i = 0 ; i < s.length() ; i++){ res += Math.pow(2, s.length()-1-i) * (s.charAt(i) -'0'); } return res; }}

bit运算

 

public class Solution {    public List
grayCode(int n) { int count = (int) Math.pow(2, n); List
res = new ArrayList<>(); for(int i = 0; i < count ; i++){ res.add(i ^ (i >> 1)); } return res; }}

 

转载于:https://www.cnblogs.com/joannacode/p/6105896.html

你可能感兴趣的文章
Qt - 设置TableWidget只读
查看>>
Lucene:信息检索与全文检索
查看>>
J2EE开发之常用开源项目介绍
查看>>
8. String to Integer (atoi)
查看>>
移动硬盘磁盘结构损坏且无法读取文件怎样恢复
查看>>
学习记录(部分myeclipse快捷键,一些面试题),有点乱,但是挺有用
查看>>
poj2114 Boatherds
查看>>
maven学习(上)- 基本入门
查看>>
20165231 实验一 Java开发环境的熟悉
查看>>
移动商城第八篇【添加商品之基本属性和大字段数据(FCK文本编辑器)】
查看>>
Solr学习总结(六)SolrNet的高级用法(复杂查询,分页,高亮,Facet查询)
查看>>
对象序列化和反序列化
查看>>
6.10
查看>>
lcd_1602
查看>>
三年工作总结
查看>>
循环不变式证明算法的正确性
查看>>
实现算法2.15、2.16的程序(一个数组只生成一个静态链表)
查看>>
java常用设计模式
查看>>
Web开发中的网络知识(传输层)
查看>>
Shell脚本8种字符串截取方法总结
查看>>