338. Counting Bits

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
求出从0到n的每一个数字的二进制形式的1的个数。

2,题目思路
如果直接用暴力的方法,很简单。直接求出每一个数字的二进制的形式的1的个数,然后返回即可。这样做的时间复杂度较高。
另外,也可以直接用C++的内置的方法,直接求一个数字的二进制的1的个数。
最后,还有一种办法是,从已经找到的数字的中寻找得到的解,然后利用这样的方法可以快速的找到目前的数字的1的个数,最后再将这个数字加入到列表中,方便之后的数字进行查找取值。

3,程序源码
方法1:(暴力)

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> res;
        for(int i = 0;i<=num;i++)
            res.push_back(binCount(i));
        return res;
    }

private:
    int binCount(int n)
    {
        int res = 0;
        while(n!=0)
        {
            res += n%2;
            n /=2;
        }
        return res;
    }

};

方法2:(内置方法bitset)

#include<bitset>

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> result(num + 1);
        for(int i = 1; i < num + 1; ++i){
            result[i] = bitset<32>(i).count();
        }
        return result;
    }
};

方法3:从已经得到的结果中寻找解以减少计算

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret(num+1, 0);
        for (int i = 1; i <= num; ++i)
            ret[i] = ret[i&(i-1)] + 1;
        return ret;
    }
};
//上面的代码中,i&(i-1)的含义为,将i的从右往左的第一个1变为0,这样可以使得i变小,以便可以从已经找到的结果中寻找结果。然后再加1给加回来即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值