序列打印
题目描述
对于给定的正整数n,格雷码为满足如下条件的一个编码序列:
(1) 序列由2^n个编码组成,每个编码都是长度为n的二进制位串。
(2) 序列中无相同的编码。
(3) 序列中位置相邻的两个编码恰有一位不同。
例如:n=2时的格雷码为:{00, 01, 11, 10}。
样例输入
3
样例输出
000
001
011
010
110
111
101
100
实验代码
说明:通过递归打印其结果。
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
void output(int* G, int lenth)
{
for (int i=0; i<lenth; i++){
printf("%d",G[i]);
}
printf("\n");
}
void GeLeiMa(int* G, int index, int lenth)
{
if(index == lenth-1){
output(G, lenth);
if (G[index] == 0) G[index] = 1;
else G[index] =0;
output(G, lenth);
}else{
GeLeiMa(G, index+1, lenth);
if (G[index] == 0) G[index] = 1;
else G[index] = 0;
GeLeiMa(G, index+1, lenth);
}
}
int main()
{
int G[20];
int n;
scanf("%d",&n);
memset(G,0,sizeof(G));
GeLeiMa(G, 0, n);
printf("\n");
return 0;
}
二进制的第i位与格雷码转换实验
说明
Grey序列的第i位为i xor (i>>1).
输出的是第i位格雷码的十进制形式。
输入
n 二进制位数
输出
n位的格雷码序列
代码
#include<vector>
#include<iostream>
using namespace std;
typedef long long LL;
int main()
{
int n;
cin>>n;
vector<int> v;
v.clear();
for(int i=0;i<(1<<n);i++) v.push_back(i^(i>>1));
vector<int>::iterator it;
for(it=v.begin();it!=v.end();it++){
cout<<*it<<endl;
}
}