LeetCode 89: Gray Code解题报告
来源:互联网 发布:mac如何安装windows10 编辑:程序博客网 时间:2024/06/05 05:57
89. Gray Code
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.
方法1: 最简单的方法,利用数学公式,对从0~2^n-1的所有整数,转化为格雷码。
方法2: n比特的格雷码,可以递归地从n-1比特的格雷码生成。如下图所示:
Gray Code 0 = 0, 下一项是toggle最右边的bit(LSB), 再下一项是toggle最右边值为 “1” bit的左边一个bit。然后重复
如: 3bit
Gray Code: 000, 001, 011, 010, 110, 111, 101, 100, 最右边值为 “1” 的bit在最左边了,结束。
Binary : 000, 001, 010, 011, 100, 101, 110, 111
再者就是Binary Code 转换为Gray Code了。
如:
Binary Code :1011 要转换成Gray Code
1011 = 1(照写第一位), 1(第一位与第二位异或 1^0 = 1), 1(第二位异或第三位, 0^1=1), 0 (1^1 =0) = 1110
其实就等于 (1011 >> 1) ^ 1011 = 1110
AC代码:
#include<iostream>#include<vector>using namespace std; class Solution {public: vector<int> grayCode(int n) { vector<int> emptyArr(0); if(n<0) return emptyArr; // 输入异常时,即n为负整数时的处理办法... if(n>=0) { int size=1<<n; vector<int> NumArr(size,0); int gNum=0; for(int i=0;i<size;i++) { gNum=i ^ i>>1; // 数学公式G[i]=i ^ i/2,gNum是一个格雷码对应的二进制数,存储时变成int(十进制) NumArr[i]=gNum; } return NumArr; } }}; /* 以下为测试 *//*int main(){ int n,j; vector<int> display; cin>>n; Solution sol; display=sol.grayCode(n); for(j=0;j<display.size();j++) { cout<<display[j]<<" "; } cout<<endl; return 0;}*/
相关链接:
2016校招腾讯研发岗笔试题(第一题 格雷码) - u010660138的博客 - CSDN http://blog.csdn.net/u010660138/article/details/48265341
- LeetCode 89: Gray Code解题报告
- [LeetCode] Gray Code 解题报告
- [leetcode] 89. Gray Code 解题报告
- Leetcode 89. Gray Code 格雷码 解题报告
- [Leetcode] 89. Gray Code 解题报告
- Gray Code解题报告
- hdu 5375 - Gray code(dp) 解题报告
- [leetcode 89] Gray Code
- LeetCode 89 Gray Code
- leetcode || 89、Gray Code
- Leetcode 89 Gray Code
- [leetcode] #89 Gray Code
- leetcode 89:Gray Code
- Leetcode #89 Gray Code
- LeetCode(89) Gray Code
- leetcode 89: Gray Code
- leetcode #89 Gray Code
- 【leetcode】【89】Gray Code
- 安装cuda问题
- 互联网协议入门(二)
- edgesForExtendedLayout、extendedLayoutIncludesOpaqueBars、automaticallyAdjustsScrollViewInsets属性详解
- softmax loss
- 纯css打造漂亮的html表格
- LeetCode 89: Gray Code解题报告
- umask与chmod
- Android TV 开发使用模拟器
- Win7 64位下PowerDesigner连接64位Oracle11g数据库
- mysql 模糊查询和正则
- 【Adb connection Error:远程主机强迫关闭了一个现有的连接】错误解决方法
- C++多态篇2——虚函数表详解之从内存布局看函数重载,函数覆盖,函数隐藏
- 收到来自其他应用程序的简单的数据
- fzu2215 中缀表达式展开求多项式系数(模拟)【中缀转后缀模板】