#T634. 格雷码

格雷码

Description

The Gray code represents numbers using n-bit binary digits.

Unlike ordinary binary representation, it requires that adjacent numbers differ by only one bit.

The first and last numbers must also differ by only one bit.

There are many algorithms to generate Gray codes. Here is one of the more common methods:

Start generating from the all-zero code.

When generating the odd-numbered code, only flip the least significant bit (0 to 1 or 1 to 0) of the current number.

When generating the even-numbered code, first find the rightmost 1, then flip the bit to its left.

Using this rule, the sequence of 4-bit Gray codes is as follows:

0000

0001

0011

0010

0110

0111

0101

0100

1100

1101

1111

1110

1010

1011

1001

1000

Below is the implementation code. Carefully analyze its logic and fill in the missing code in the underlined part.

```cpp #include void show(int a,int n){ int i; int msk = 1; for(i=0; i<n-1; i++) msk = msk << 1; for(i=0; i<n; i++){ printf((a & msk)? "1" : "0"); msk = msk >> 1; } printf("\n"); } void f(int n){ int i; int num = 1; for(i=0; i<n; i++) num = num<<1; int a = 0; for(i=0; i<num; i++){ show(a,n); if(i%2==0){ a = a ^ 1; } else{ a = _________________________ ; //填空 } } } int main(){ f(4); return 0; } ``` ## Input Format

None

Output Format

Note: Only fill in the missing content in the underlined parts. Do not copy existing code or symbols.

```input1 无 ``` ```output1 0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111 1110 1010 1011 1001 1000
## Hint

<p><span style="color: rgb(77, 77, 77);">Note: Only fill in the missing content for the underlined parts. Do not copy existing code or symbols.

## Source

2018 9th Lanqiao Cup C/C++ Group B National Finals Original Questions