每日一题 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;
    }
};
相关推荐
漫随流水21 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
千金裘换酒1 天前
LeetCode反转链表
算法·leetcode·链表
圣保罗的大教堂1 天前
leetcode 1161. 最大层内元素和 中等
leetcode
闲看云起1 天前
LeetCode-day6:接雨水
算法·leetcode·职场和发展
黛色正浓1 天前
leetCode-热题100-贪心合集(JavaScript)
javascript·算法·leetcode
一起努力啊~1 天前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
leoufung1 天前
LeetCode 221:Maximal Square 动态规划详解
算法·leetcode·动态规划
源代码•宸1 天前
Leetcode—39. 组合总和【中等】
经验分享·算法·leetcode·golang·sort·slices
好易学·数据结构1 天前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
AlenTech1 天前
226. 翻转二叉树 - 力扣(LeetCode)
算法·leetcode·职场和发展