Gray Code
来源:互联网 发布:淘宝外卖订餐网 编辑:程序博客网 时间:2024/06/18 11:38
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.
//整数n 的格雷码是n ^ (n/2)。
class Solution {public: vector<int> grayCode(int n) { vector<int> rst;size_t size = 1 << n;//2^nrst.reserve(size);for (size_t i = 0; i < size; i++)rst.push_back(i ^ (i >> 1));return rst; }};
vector的reserve()与resize()函数区别:
- vector 的reserve增加了vector的capacity,但是它的size没有改变!而resize改变了vector的capacity同时也增加了它的size!
- reserve是容器预留空间,但在空间内不真正创建元素对象,所以在没有添加新的对象之前,不能引用容器内的元素。加入新的元素时,要调用push_back()/insert()函数。
- resize是改变容器的大小,且在创建对象,因此,调用这个函数之后,就可以引用容器内的对象了,因此当加入新的元素时,用operator[]操作符,或者用迭代器来引用元素对象。此时再调用push_back()函数,是加在这个新的空间后面的。
0 0
- Gray Code
- Gray Code
- gray code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Tomcat绑定IPV4端口
- IP0.0.0.0
- HDU-1394-Minimum Inversion Number
- poj 3522 Slim Span
- linux mail发邮件
- Gray Code
- 递归求1!+2!+3!+...+n!
- Redhat 5.9下不识别命令ifconfig
- Service以及AIDL学习
- Android之Activity,Fragment生命周期探知
- 安装JDK8
- shiro 简介 (三)
- JAVA字符串格式化-String.format()和MessageFormat的使用
- 表格table