C bit xor operation casts about 4ms


  • 0
    S

    Use xor operation, from 0 to 2^n, check the last binary bit which is not ZERO, use xor with the last number.

    int* grayCode(int n, int* returnSize) {
        *returnSize=1<<n;
        unsigned int* pAns=(unsigned int*)malloc(*returnSize*sizeof(unsigned int));
        pAns[0]=0;
        for (unsigned int i=1;i<*returnSize;i++){
            unsigned int temp=i;
            for (int j=0;j<n;j++){//xor the last bit which is not zero
                if (temp%2!=0){
                    pAns[i]=pAns[i-1]^(1<<j);
                    break;
                }
                temp=temp>>1;
            }
        }
        return pAns;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.