每日一题 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;
    }
};
相关推荐
Demons_kirit10 小时前
Leetcode 2845 题解
算法·leetcode·职场和发展
Wendy_robot12 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.13 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
Y1nhl15 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
前端 贾公子15 小时前
详解 LeetCode 第 242 题 - 有效的字母组
算法·leetcode·职场和发展
Demons_kirit17 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行17 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
雾月5519 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++19 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
এ᭄画画的北北20 小时前
力扣-160.相交链表
算法·leetcode·链表