每日一题 338. 比特位计数

338. 比特位计数

难点是发现规律

cpp 复制代码
class Solution {
public:
    vector<int> countBits(int n) {
        
        vector<int> dp(n+1,0);
        if(n <=0)
        {
            return dp;
        }
        dp[1] = 1;
        if(n == 1)
        {
            return dp;
        }
        int bin = 0;
        for(int i=2;i<=n;++i)
        {
            int base = getBinary(i);
            dp[i] = dp[i-(1<<base)] + 1; 
        }
        return dp;
    }

    int getBinary(int num)
    {
        int ret = 0;
        while( num != 0)
        {
            num  = num >> 1;
            ++ret;
        }
        return ret-1;
    }
};
相关推荐
We་ct27 分钟前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
Navigator_Z1 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
lightqjx2 小时前
【算法】前缀和
c++·算法·leetcode·前缀和
窝子面2 小时前
LeetCode练题三:链表
算法·leetcode·链表
y = xⁿ3 小时前
【LeetCodehot100】T108:将有序数组转换为二叉搜索树 T98:验证搜索二叉树
数据结构·算法·leetcode
hanlin034 小时前
刷题笔记:力扣第17题-电话号码的字母组合
笔记·算法·leetcode
阿Y加油吧4 小时前
力扣打卡day09——缺失的第一个正数、矩阵置零
数据结构·算法·leetcode
灰色小旋风4 小时前
力扣16 最接近的三数之和(C++)
数据结构·c++·算法·leetcode
Tisfy5 小时前
LeetCode 3643.垂直翻转子矩阵:原地修改
算法·leetcode·矩阵·模拟
Storynone5 小时前
【Day29】LeetCode:62. 不同路径,63. 不同路径 II,343. 整数拆分,96. 不同的二叉搜索树
python·算法·leetcode