Skip to content

Instantly share code, notes, and snippets.

@shitu13
Created June 4, 2024 09:41
Show Gist options
  • Save shitu13/2e37076e7161353fea7efd682b76c9f2 to your computer and use it in GitHub Desktop.
Save shitu13/2e37076e7161353fea7efd682b76c9f2 to your computer and use it in GitHub Desktop.
Counting Bits
// Approach 1
// Complexity: O(n*log n)
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans;
for(int i=0; i<=n; i++){
ans.push_back(__builtin_popcount(i));
}
return ans;
}
};
// Approach 2
// Complexity: O(n)
class Solution {
public:
vector<int> countBits(int n) {
vector<int> res(n + 1);
if (n == 0)
return res;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0)
res[i] = res[i / 2];
else
res[i] = res[i / 2] + 1;
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment