C solution, 40ms


  • 0
    T
    //the lower sub-array is used to calculate subsequent values
    //add 1 to every element of the sub-array (element 0 to subSize-1)
    //and copy this to the end of result array
    int* countBits(int num, int* returnSize) {
            
        *returnSize = num+1;
        int* counts = calloc(*returnSize, sizeof(int));
        
        int subSize = 1; 
        counts[0] = 0;
        
        for(int i = 0 ; i < num;){
            for(int j = 0 ; j < subSize && i < num ; j++,i++)
                counts[i+1] = counts[j]+1;
                
            //double the subSize
            subSize = subSize << 1;
        }
        
        return counts;
    }

Log in to reply
 

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