Leetcode88: Gray Code
2015-10-09 10:04
190 查看
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
is:
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.
数学解:
从第0个开始,第i个gray code为:(i>>1)^i
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.
数学解:
从第0个开始,第i个gray code为:(i>>1)^i
class Solution { public: vector<int> grayCode(int n) { vector<int> res; int num = 1<<n; int i = 0; while(i<num) { res.push_back((i>>1)^i); i++; } return res; } };
相关文章推荐
- SSO单点登录在互联网电商应用中的解决方案(基于CAS的改造)
- B树、B-树、B+树、B*树
- 微信浏览器取消缓存的方法
- Html 图像
- 每天一个linux命令(25):linux文件属性详解
- oracle 导出表
- 全融合网络虚拟化技术
- linux中的awk
- svm中的数学和算法
- java——List
- jQuery拖动布局其结果保存到数据库
- java的泛型
- request.getparameter、request.getattribute 区别
- Android bootchart分析
- 理解OAuth 2.0
- 删除单链表的头元素;单链表,只是遍历一次,求出中间节点
- --##,__VA_ARGS__, __FILE__, __FUNCTION__
- C#开发微信门户及应用(8)-微信门户应用管理系统功能介绍
- 消遣系列
- 事件监听,按钮监听,fireEvent