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");
}
}