LeetCode OJ:Gray Code(格林码)
2015-11-21 16:34
363 查看
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
看着好像很难的样子,但是实际上就是一个二进制码到格林吗的转换而已,代码如下(这个本科的时候好像学过,但是不记得了,看了下别人的):
java版本的代码如下所示:
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
看着好像很难的样子,但是实际上就是一个二进制码到格林吗的转换而已,代码如下(这个本科的时候好像学过,但是不记得了,看了下别人的):
class Solution { public: vector<int> grayCode(int n) { int total = 1 << n; vector<int> ret; for(int i = 0; i < total; ++i){ ret.push_back(i>>1^i); } return ret; } };
java版本的代码如下所示:
public class Solution { public List<Integer> grayCode(int n) { List<Integer> ret = new ArrayList<Integer>(); int num = 1 << n; for(int i =0 ; i< num; ++i){ ret.add(i>>1^i); } return ret; } }
相关文章推荐
- PLSQL Developer 完美支持Oracle64位问题
- 函数指针的声明与使用
- matlab:创建cell结构体
- c++11线程管理,RAII方式等待异常环境下线程结束
- linux 常用基础命令 chkconfig 详细介绍
- codeforces round #332
- [笔记] Convex Optimization 2015.11.18
- 索引 概述
- Markdown简介
- 在Linux里设置环境变量的方法(export PATH)
- 话说正确率、召回率和F值
- win7系统怎么用笔记本做wifi热点
- Loadrunner11不能调用IE8解决方法大全
- python模块之JSON
- centos6.5安装Mysql5.6版本
- NYOJ 17 单调递增最长子序列(LIS)
- AnkhSVN 安装
- android handler机制简单介绍
- C语言简单实现接口
- 神经网络训练中的训练集、验证集以及测试集合