#T431. 格雷码
格雷码
Description
Gray code is an n-bit binary representation of numbers.
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 code. The following 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.
The 4-bit Gray code sequence generated using this rule is as follows:
0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
The implementation code is provided below. 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.
## Hint
<p><span style="color: rgb(77, 77, 77);">Note: Only fill in the missing content in the underlined parts. Do not copy existing code or symbols.
## Source
2018 9th Lanqiao Cup C/C++ Group B National Finals Real Questions