Leetcode 89. Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

分析

灰碼序列,就是二進制形式的各位只有一個相反。我是用的方法是,從0開始,依次翻轉(zhuǎn)一個位,如果新數(shù)字未出現(xiàn)過,就加到結(jié)果數(shù)組中。然后對該數(shù)進一步翻轉(zhuǎn)其中的一個位。該方法循環(huán)次數(shù)較多,比較慢。
網(wǎng)上有其他方法,找到了該規(guī)律: G(i) = i^ (i/2).可以使用。

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* grayCode(int n, int* returnSize) {
    int *ans=(int*)malloc(sizeof(int)*1000000);
    ans[0]=0;
    *returnSize=1;
    int max=1;
    
    for(int i=0;i<n;i++)
        max=max*2;
    for(int i=1;i<max;i++)
    {
        for(int j=0;j<n;j++)
        {
            int temp=ans[*returnSize-1]^(1<<j);
            int k=0;
            for(k=0;k<*returnSize;k++)
            {
                if(ans[k]==temp)break;
            }
            if(k<*returnSize)
                continue;
            else
            {
                ans[*returnSize]=temp;
                *returnSize=*returnSize+1;
                break;
            }
        }
    }
    return ans;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容