Last active
July 2, 2021 00:07
-
-
Save Rushi98/6a1103aa64ac351a58225adcbec8dd40 to your computer and use it in GitHub Desktop.
Gray Code https://leetcode.com/explore/item/3799
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
/** | |
* Note: The returned array must be malloced, assume caller calls free(). | |
*/ | |
int* grayCode(int n, int* returnSize) { | |
int size = 1 << n; // 2 ^ n | |
int *sequence = (int *) calloc(size, sizeof(int)); | |
sequence[0] = 0; | |
sequence[1] = 1; | |
for (int bitcount = 2; bitcount <= n; bitcount++) { | |
int curSeqSize = 1 << bitcount; | |
int lastSeqSize = curSeqSize / 2; | |
// first half: i -> (i << 1) | |
// Ex. bitcount = 2 | |
// 1) 0 -> 00 | |
// 2) 1 -> 10 | |
for (int i = 0; i < lastSeqSize; i++) { | |
// printf("%d) %d -> ", i + 1, sequence[i]); | |
sequence[i] <<= 1; | |
// printf("%d\n", sequence[i]); | |
} | |
// second half: i -> (i << 1 + 1) in reverse order | |
// Ex. bitcount = 2 | |
// 3) 1 -> 10 + 1 -> 11 | |
// 4) 0 -> 00 + 1 -> 01 | |
for (int i = 0; i < lastSeqSize; i++) { | |
// printf("%d) %d -> ", lastSeqSize + i + 1, sequence[lastSeqSize - i - 1]); | |
sequence[lastSeqSize + i] = sequence[lastSeqSize - i - 1] + 1; | |
// printf("%d\n", sequence[lastSeqSize + i]); | |
} | |
} | |
*returnSize = size; | |
return sequence; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://leetcode.com/submissions/detail/516069861/