89. Gray Code
来源:互联网 发布:太阳社玻尿酸原液 知乎 编辑:程序博客网 时间:2024/05/22 01:32
Problem:
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表示一个二进制的位数,然后输出所有二进制对应的格雷码所对应的十进制值。而且这里讨论的是比较自然的格雷码的排序。也就是从十进制的顺序。格雷码的定义:
https://baike.baidu.com/item/%E6%A0%BC%E9%9B%B7%E7%A0%81
题意是很简单,但是做法我觉得不是很好想,效率不是很高,因为根据格雷码的定义,需要两两异或,所以时间肯定是O(2^n)级别的。
然后我去查找了一下,发现了一个关于格雷码的数学公式:G(n) = n xor (n/2),所以代码如下:
Code:(LeetCode运行6ms)
class Solution {public: vector<int> grayCode(int n) { //2^n种gray码 int size = 1 << n; vector<int> result; for (int i = 0; i < size; i++) { result.push_back(IntToGray(i)); } return result; } int IntToGray(int i) { return i ^ (i >> 1); }};
- [LeetCode]89.Gray Code
- LeetCode 89. Gray Code
- [Leetcode] 89. Gray Code
- LeetCode --- 89. Gray Code
- [leetcode] 89.Gray Code
- 89. Gray Code
- 89. Gray Code
- 89. Gray Code LeetCode
- 89. Gray Code
- [LeetCode]89. Gray Code
- 89. Gray Code
- 89. Gray Code
- 89. Gray Code
- Leetcode 89. Gray Code
- [leetcode] 89. Gray Code
- 89. Gray Code
- LeetCode *** 89. Gray Code
- 89. Gray Code
- 机器学习中的必修数学(六)
- form表单提交与input的关系,以及jquery调用按钮的问题
- 判断文件是否存在,不存在则新建
- 【安全牛学习笔记】Burpsuite-repeater,Sequencer,编码,代理截断工具
- c++ enum类型
- 89. Gray Code
- CSDN新版博客feed流内测用户征集令
- 9、Spring技术栈-整合dubbo、zookeeper
- Android界面展示效果心得(随时更新)
- cocos2d-x引用机制
- 结合Wireshark分析DNS 协议
- spring cloud config 用svn做配置文件仓库
- AJAX学习笔记(四)_ onreadystatechange 事件
- Word这些操作技巧,你会与不会只差这篇文章的距离,关键你想不想