338. Counting Bits

​ 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 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [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.


个人认为这道题目的意图就在于寻找规律,因为相邻两个数字的二进制形式是有很大的联系的,请看下面的例子:(2‘1 表示数字2的二进制形式中的1的个数)

二进制数的位数原数字二进制形式1的数字备注
1000
11110‘1 + 1
221010‘1 + 1
231121‘1 + 1
3410010‘1 + 1
3510121‘1 + 1
3611022‘1 + 1
3711133’1 + 1
48100010’1 + 1
49100121‘1 + 1
410101022‘1 + 1
411101133‘1 + 1
412110024‘1 + 1
413110135‘1 + 1
414111036‘1 + 1
415111147‘1 + 1
5161000010‘1 + 1
5171000121‘1 + 1
5181001022‘1 + 1

从上表中可以看出,二进制形式长度为i的数字集合的二进制形式的1的个数是二进制形式长度<i的数字集合的二进制形式的1的个数+1,这句话有点绕,总之,计算二进制形式长度为223的二进制中的1的个数,正是数字01的二进制中的1的个数+1,同样4’1 = 1 + 0'15’1 = 1 + 1'16’1 = 1 + 2'17’1 = 1 + 3'1。正是如此一种规律。因此可以得出下面的代码:

vector<int> countBits(int num)
{
    if(num < 0)return {};
    vector<int> result{0};
    if(num == 0)return result;
    while(true)
    {
        int cur_size = result.size();
        for(int i = 0; i < cur_size; i++)
        {
            result.push_back(result[i] + 1);
            if(result.size() > num)return result;
        }
    }
    return result;
}

www.sunshangyu.top

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值