leetcode 比特位计数

略微有一点那啥的事,我找到了那个状态转移方程,我却不会dp

这个题,you know,比如9(1001)就是比那个2^3多了bits[9-8]个一,所以是一定能状态转移到较小的数上来的

这里有一个判断2^n的公式:

x&(x-1)==0 当且仅当为2^n

然后这个题基本就出来了,动态规划

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> bits(num + 1);
        int highBit = 0;
        for (int i = 1; i <= num; i++) {
            if ((i & (i - 1)) == 0) {
                highBit = i;
            }
            bits[i] = bits[i - highBit] + 1;//原来的那个bits[i-highBit]+最高位的1
        }
        return bits;
    }
};


为了自己,和那些爱你的人
原文地址:https://www.cnblogs.com/zhmlzhml/p/14474506.html