LeetCode 338 :Counting Bits

6 篇文章 0 订阅

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].

1、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?
2、Space complexity should be O(n).
3、Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

解:如果直接一个个数字辗转相除求余计算的话时间复杂度就为O(n*sizeof(integer)),可以发现,对于二进制表示中1的个数,由于是连续的自然数
组一:
0:0000
1:0001
组二:
2:00 1 0
3:00 1 1
比组一刚好每一个多了一个‘1’(即第二位的‘1’)
组四:
4:0 1 00
5:0 1 01
6:0 1 10
7:0 1 11
把组一组二合起来看做组3,则组四每一个都比组三对应的多一个‘1’(即第3位的‘1’)

vector<int> countBits(int num) {
    vector<int> res;
    res.push_back(0);
    int count = 0;
    if(num == 0)
        return res;
    //每次取2的幂数个数
    for(int k = 0; k < 100000; k++)
        for(int i = 0; i < pow(2,k); i++)
        {
            int nowRes = res[i] + 1;
            res.push_back(nowRes);
            count++;
            if(count == num)
                return res;
        }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值