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;
}
};