Sicily 1721. Gray code

Time Limit: 1 secs, Memory Limit: 32 MB , Special Judge

Description

Gray code is an interesting code sequence and has many applications in computer science. No matter you have known it before or not, here are some introductions about its features:
(1)Gray code has 2n unique elements;
(2)Each element contains n digits of 0 or 1;
(3)Each pair of adjacent elements has exactly one different digit.
For example, when n=2, one of the gray code sequences is: 00,01,11,10.
Now, the task is quite simple, given a positive integer n, generate the corresponding Gray code sequence.

Input

Input may contain multiple test cases. Each test case consists of one positive integer n(n<=16), Input is terminated by a case with n=0, which should not be processed.

Output

For each test case, output the corresponding Gray code sequence, one element per line. There may be multiple answers, any of them will be accepted. Please output a blank line after each test case.

Sample Input

1
2
0

Sample Output

0
1

00
01
11
10


(~ ̄▽ ̄)~ 生成格雷码,参考百度百科

Just do it!

#include <string.h>
#include <stdio.h>
#include <math.h>

using namespace std;

int main()
{
    int num, i, j;
    char code[16], gray[17];
    while (scanf_s("%d", &num) && num)
    {
        memset(code, '0', sizeof(code));
        gray[num] = '\0';
        for (i = pow(2, num); i > 0; i--) {
             二进制码转换为格雷码
            gray[0] = code[0];  // 最高位不变
            for (j = 1; j < num; j++)
                gray[j] = (code[j - 1] == code[j] ? '0' : '1');
            printf("%s\n", gray);

             二进制码++
            for (j = num - 1; j >= 0; j--) {
                code[j] = (code[j] == '1' ? '0' : '1');
                if (code[j] == '1')
                    break;
            }
        }
        printf("\n");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值