topic:
Given a non-negative integer num. For 0 ≤ i ≤ i, each digital num range, which calculates the number of binary digits 1 and returns them as an array.
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Advanced:
Given time complexity is O (n * sizeof (integer) ) answers very easy. But you can in linear time O (n) with one pass do it?
The space requirements of the algorithm complexity is O (n).
You can further improve the solution it? Request does not use any built-in functions (e.g., in __builtin_popcount C ++) in C ++ or any other language to do this.
Code:
class Solution {
public:
vector<int> countBits(int num) {
vector<int>ans;
ans.insert(ans.end(), 0);
for (int i = 1; i <= num; i++)
{
ans.insert(ans.end(), i % 2 + ans[i / 2]);
}
return ans;
}
};