Counting Bits
Description
Solutions
My solution
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num + 1);
for(int i = 1; i <= num; ++i){
if(i % 2)
ans[i] = ans[i - 1] + 1;
else{
int count = ans[((i - 1) ^ i) >> 1];
ans[i] = ans[i - 1] - count + 1;
}
}
return ans;
}
};Optimal solution
Last updated