338.counting bits
Problem Statement:¶
- Given an integer
n, return an arrayansof lengthn + 1such that for eachi(0 <= i <= n),ans[i]is the number of1's in the binary representation ofi.
Approach¶
- We could use previous solution as in 191.number-of-1-bits which calculates in
O(logN)time and call itntimes to get final solution innlogntime. - do a DP solution
- for every even number, the number of 1 bits are exactly equal to that of it's parent in a tree,
- for example the
1bits in number 4(100) are equal to bits in number 2(10) and so on
- for example the
- for every odd number, the number of 1 bits are
+1of its parent- for example the 1 bits in
21(10101)are exactly equal to10(1010) + 1
- for example the 1 bits in
- for every even number, the number of 1 bits are exactly equal to that of it's parent in a tree,
###### Code:
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans = {0};
for(int i = 1; i <= n; i++){
ans.push_back(ans[i/2]);
if(i%2)
ans[i] += 1;
}
return ans;
}
};