LeetCode - Gray Code
2016-01-04 08:37
260 查看
题目:
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
Note:
For a given n, a gray code sequence is not uniquely defined.
For example,
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
思路:
移位运算
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.
思路:
移位运算
package math; import java.util.ArrayList; import java.util.List; public class GrayCode { public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>(); if (n < 0) return res; res.add(0); int count = 0; while (count < n) { for (int i = res.size() - 1; i >= 0; --i) { res.add(res.get(i) + (1 << count)); } ++count; } return res; } public static void main(String[] args) { // TODO Auto-generated method stub GrayCode g = new GrayCode(); for (int i : g.grayCode(3)) System.out.println(i); } }
相关文章推荐
- 1217 递归下降语法分析程序设计
- 基于TFTP协议的远程升级设计
- 奖学金(0)<P2007_1>
- 关于WM_NOTIFY及反射机制的来龙去脉
- 数据库中substring的用法 CONVERT(varchar(12) , getdate(), 112 )
- sql while 遍历表
- 注册界面的优化之ActionBar组件的应用之(二)ActionBar组件的事件处理
- 七星彩问题
- Windows平台分布式架构实践 - 负载均衡
- (转)JAVA中short和short相加自动转化为int
- ISBN号码(0)<P2008_1>
- nmon和nmon analyser的下载和使用
- POJ--1936 All in All(水题,暴力即可)
- 如何在QML中使用不同的字体(font)
- POJ--1936 All in All(水题,暴力即可)
- Lind.DDD.Messaging框架通讯组件介绍
- (转)java中short类型变量
- 多项式输出 (0)<P2009_1>
- Win10 Mobile正式版全新Aero毛玻璃特效概念图曝光
- HTML转为markdown工具