solution.cpp 538 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <stdio.h>
#include <stdlib.h>
int *grayCode(int n, int *returnSize)
{
	if (n < 0)
	{
		return NULL;
	}
	int i, count = 1 << n;
	int *codes = malloc(count * sizeof(int));
	for (i = 0; i < count; i++)
	{
		codes[i] = (i >> 1) ^ i;
	}
	*returnSize = 1 << n;
	return codes;
}
int main(int argc, char **argv)
{
	if (argc != 2)
	{
		fprintf(stderr, "Usage: ./test n\n");
		exit(-1);
	}
	int i, count;
	int *list = grayCode(atoi(argv[1]), &count);
	for (i = 0; i < count; i++)
	{
		printf("%d ", list[i]);
	}
	printf("\n");
	return 0;
}