格雷码打印实验

序列打印

题目描述

对于给定的正整数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;
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值