Leetcode刷题记录-比特位计数

先放Leetcode的四种方法,后边是我自己的理解与证明。

1.Brian Kernighan 算法->n&(n-1)可以消去二进制数n的末位1

2. 动态规划

 (1)最高有效位

(2)最低有效位  

(3)最低设置位

 

下面为可运行代码:

#include <iostream>
#include <vector>
using namespace std;
//比特位计数
// Kernighan算法
class Solution1
{
public:
    int countones(int n)
    {
        int num = 0;
        while (n > 0)
        {
            n &= (n - 1);
            num++;
        }
        return num;
    }
    vector<int> countbits(int n)
    {
        vector<int> bits(n + 1);
        for (int i = 0; i <= n; i++)
        {
            bits[i] = countones(i);
            cout << bits[i] << "  ";
        }
        return bits;
    }
};
//动态规划-最高有效位
class Solution2
{
public:
    vector<int> countBits(int n)
    {
        vector<int> bits(n + 1);
        int high = 0;
        bits[0] = 0;
        cout << bits[0] << "  ";
        for (int i = 1; i <= n; i++)
        {
            if ((i & (i - 1)) == 0)
            {
                high = i;
            }
            bits[i] = bits[i - high] + 1;
            cout << bits[i] << "  ";
        }
        return bits;
    }
};
//动态规划-最低有效位
class Solution3
{
public:
    vector<int> countBits(int n)
    {
        vector<int> bits(n + 1);
        cout << bits[0] << "  ";
        for (int i = 1; i <= n; i++)
        {
            bits[i] = bits[i >> 1] + (i & 1);
            cout << bits[i] << "  ";
        }
        return bits;
    }
};
//动态规划-最低设置位
class Solution4
{
public:
    vector<int> countBits(int n)
    {
        vector<int> bits(n + 1);
        cout << bits[0] << "  ";
        for (int i = 1; i <= n; i++)
        {
            bits[i] = bits[i & (i - 1)] + 1 ;
            cout << bits[i] << "  ";
        }
        return bits;
    }
};
int main()
{
    Solution1 S1;
    S1.countbits(10);
    cout << endl;
    Solution2 s2;
    s2.countBits(10);
    cout << endl;
    Solution3 s3;
    s3.countBits(10);
    cout << endl;
    Solution4 s4;
    s4.countBits(10);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MayPP___

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值