LeetCode 338. Counting Bits (Medium)

题目描述:

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

Example:
num = 5 you should return [0,1,1,2,1,2].
题目大意:给出一个整数num,求0到num的所有数字的二进制形式的所有1的个数。(如5(101)含2个1)。

思路:把0-15的二进制形式写出来观察:

十进制二进制1的个数
0000
1011
2101
3112
41001
51012
61102
71113
810001
910012
1010102
1110113
1211002
1311013
1411103
1511114

观察,不妨把二进制的位数规定为1可能出现的最高位。那么可以给数字分组,比如0123是一组(2位),4567是一组(3位),8-15是一组(4位)。再观察可以得到:第n组数字是前n-1组所有对应数字扩展一位,并且那一位为1(相当于进位)。知道这个规律之后好做了:打表。

c++代码:

class Solution {
public:
    vector<int> countBits(int num) 
{
    vector<int> ans;
    ans.push_back(0);
    ans.push_back(1);
    ans.push_back(1);
    ans.push_back(2);
    while (ans.size() < num + 1)
    {
        int o_size = (2 * ans.size()) > (num + 1) ? num + 1 - ans.size() : ans.size();
        for (int i = 0; i < o_size; i++)
        {
            ans.push_back(ans[i] + 1);
        }
    }
    while (ans.size() > (num + 1))
    {
        ans.pop_back();
    }
    return ans;
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值