LeetCode:. 89 Gray Code Gray code (C language)

Title Description:
Gray code is a binary number system, in this system, only two successive values of a difference in number of bits.

Given a total number of bits representing an encoded non-negative integer n, which is the print gray coding sequence. Gray coding sequence must begin with 0.

Example 1:

Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 -. 1
. 11 -. 3
10 - 2

For a given n, which is not unique Golay coding sequence.
For example, [0,2,3,1] Gray coding is also a valid sequence.

00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

Input: 0
Output: [0]
Explanation: We define Golay coding sequence must start with 0.
The total number of bits to encode a given Golay coding sequence of n, has a length of 2n. When n = 0, length 20 = 1.
Thus, when n = 0, which is a Gray code sequence [0].

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/gray-code
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* grayCode(int n, int* returnSize)
{
    int len = 0;
    int i = 0;
    len = 1 << n;
    int *a = malloc(sizeof(int)*len);
    
    for(i = 0;i<len;i++)
    {
        a[i] = i^(i>>1);
    }

    *returnSize = len;

    return a;

}

Operating results :
Here Insert Picture Description

Published 123 original articles · won praise 111 · views 240 000 +

Guess you like

Origin blog.csdn.net/wangqingchuan92/article/details/104341827