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;
}