经典算法-统计0~n之间的数字二进制的1的个数

经典算法-统计0~n之间的数字二进制的1的个数

  1. 题目描述:
    给定一个数字n,统计0~n之间的数字二进制的1的个数,并用数字输出
  2. 例子:
    当n = 5 时 返回的结果应该是:[0,1,1,2,1,2]
  3. 要求:
    • 算法复杂度o (n)
    • 空间复杂度o (n)
  4. 思路分析:
    • 根据题目的要求,时间和空间复杂度,明显是要用动态规划的方法
    • 得出推到公式:f(n) = 不大于f(n)的最大的2的次方+f(k),k一定是再前面出现的,用数组记录,直接查询
    • 举例 f(5) = f(4) + f(1), 注意2的次方都是一个1,而且是最高位,f(5) = 1 + f(1), f(6) = 1 + f(2)直到f(8) = 1
 public int[] countBits(int num){
        int[] res = new int[num + 1];
        int pow2 = 1;
        int before = 1;
        for(int i = 1; i <= num;i++){
            if(i == pow2){
                before = res[i]  = 1;
                pow2 <<= 1;
            }else{
                res[i] = res[before] + 1;
                before += 1;
            }
        }
        return res;
    }

原文描述:

Given a non negative integer number num. For every nubmers 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值