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開始,依次翻轉一個位,如果新數字未出現過,就加到結果數組中。然后對該數進一步翻轉其中的一個位。該方法循環次數較多,比較慢。
網上有其他方法,找到了該規律: 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;
}