Created
June 4, 2024 09:41
-
-
Save shitu13/2e37076e7161353fea7efd682b76c9f2 to your computer and use it in GitHub Desktop.
Counting Bits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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