My 40ms c solution


  • 0
    Q
        /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* countBits(int num, int* returnSize) {
        int i = 1;
        int cnt = 0;
        int *retarr = (int *)malloc((num + 1)*sizeof(int));
        retarr[0] = 0;
        for (;i <= num;i++) {
            if (i % 2) {
                cnt++;
            } else {
                if ((i & (i - 1)) == 0) {
                    cnt = 1;
                } else {
                    cnt = retarr[i-1] - retarr[i ^ (i - 1)] + 2;
                }
            }
            retarr[i] = cnt;
        }
        if (returnSize) *returnSize = num + 1;
        return retarr;
    }

Log in to reply
 

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