Total Accepted: 20178
Total Submissions: 36151
Difficulty: Medium
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
clclass Solution {
public:
vector<int> countBits(int num) {
vector<int>ans;
ans.push_back(0);
int res=0;
for(int i=1;i<=num;i++)
{
if((i&(i-1))==0)
{
res=i;
ans.push_back(1);
}
else
{
ans.push_back(ans[i-res]+1);
}
}
return ans;
}
};