forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
07ba441
commit df56917
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test gray_code.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
/** | ||
** Return an array of size *returnSize. | ||
** Note: The returned array must be malloced, assume caller calls free(). | ||
**/ | ||
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; | ||
} |