比特位计数 leetcode 338

简介

问题的答案就在问题之中
问题说不允许使用 如 C++ 中的 __builtin_popcount
那么我们知道了可以用的为什么不去试试呢?

参考连接

https://leetcode-cn.com/problems/counting-bits/solution/hen-qing-xi-de-si-lu-by-duadua/
https://leetcode-cn.com/problems/counting-bits/

code

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

另一种方法是使用动态规划

vector<int> countBits(int num) {
        vector<int> result(num+1);
        result[0] = 0;
        for(int i = 1; i <= num; i++)
        {
            if(i % 2 == 1)
            {
                result[i] = result[i-1] + 1;
            }
            else
            {
                result[i] = result[i/2];
            }
        }
        
        return result;
    }

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14474972.html