【LeetCode-338】 Counting Bits

来源:互联网 发布:第八课网络旅行 编辑:程序博客网 时间:2024/06/06 13:23

原题:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

题目大意:

给一个非负整数num,输出[0,num]间每一个数字的二进制表示中1的个数。

思路:
把前几个值动手写一写,很快就能发现迭代规律,构建出如下图的二叉树。


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



0 0
原创粉丝点击