leetcode 338. Counting Bits

Orignal question can be found here.

My solution is as follows:

int* countBits(int num, int* returnSize)
{
        *returnSize = num+1;
        int *result = (int*) malloc(sizeof(int)*(*returnSize));
        result[0] = 0;

        for(int i=1; i<=num; ++i)
                if(i%2 == 0)
                        result[i] = result[i/2];
                else
                        result[i] = result[i-1]+1;

        return result;

}

Leave a Reply