Gray Code
来源:互联网 发布:mac medium rare 编辑:程序博客网 时间:2024/06/10 09:03
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.
思路:最开始用的方法是递归,例如,n=3可以看成是n=2的结果尾巴添加n=2的结果加上2的2次方的倒序。
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
if(n==0){
result.push_back(0);
return result;
}
if(n==1){
result.push_back(0);
result.push_back(1);
return result;
}
result=grayCode(n-1);
int size=result.size();
int i=size-1;
int temp;
for(;i>=0;--i){
temp=size+result[i];
result.push_back(temp);
}
return result;
}
};
第二种方便的思路是将二进制码右移一位与本身异或即可得到结果
- 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
- Xcode统计项目代码行数
- E: Sub-process /usr/bin/dpkg returned an error code (1)错误解决
- 技术男的春天
- MySQL Sleep 优化 系统变量interactive_timeout 与 wait_timeout
- 打印水仙花数和总个数(水仙花数是各个位的立方和等于该整数的三位数
- Gray Code
- MySQL中IN (字符串)
- HDU 1003 Max Sum
- android短信拦截
- 查找 -数据结构
- hadoop mapreduce依赖第三方jar的处理方式
- QT5BOOK 2 Get Started
- 打印*三角形
- Ubuntu Linux硬盘分区引导程序