c++
class Solution {
public:
vector<int> countBits(int num) {
if (num < 0) return vector<int>();
vector<int> res;
for (int i = 0; i <=num; ++i) {
res.push_back(popcount(i));
}
return res;
}
private:
unordered_map<int, int> cache;
int popcnt(int u)
{
int ret = 0;
while (u){
if (cache.find(u) == cache.end()) {
ret++;
u = (u & (u - 1));
}else{
ret += cache[u];
break;
}
}
cache[u] = ret;
return ret;
}
unsigned popcount(unsigned u)
{
u = (u & 0x55555555) + ((u >> 1) & 0x55555555);
u = (u & 0x33333333) + ((u >> 2) & 0x33333333);
u = (u & 0x0F0F0F0F) + ((u >> 4) & 0x0F0F0F0F);
u = (u & 0x00FF00FF) + ((u >> 8) & 0x00FF00FF);
u = (u & 0x0000FFFF) + ((u >> 16) & 0x0000FFFF);
return u;
}
};
python
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
res = [bin(x).count('1') for x in xrange(num+1)]
return res
reference:
http://tieba.baidu.com/p/2091797373
http://blog.youkuaiyun.com/gaochao1900/article/details/5646211