/* The purpose of this function is to convert an unsigned binary number to reflected binary Gray code. The operator >> is shift right. The operator ^ is exclusive or. */ unsignedintbinaryToGray(unsignedint num) { return (num >> 1) ^ num; }
把上述代码应用到本题,具体代码如下:
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * Note: The returned array must be malloced, assume caller calls free(). */ int* grayCode(int n, int* returnSize) { int length = pow(2, n); int *result = (int *)malloc(sizeof(int) * length); for(int i = 0; i < length; i++) { *(result+i) = (i >> 1) ^ i; } *returnSize = length; return result; }