add: 220301 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-01 23:45:37 +08:00
parent 32d4d04204
commit f96d8bc6cb
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 25 additions and 1 deletions

24
cpp/2203/220301.cpp Normal file
View File

@ -0,0 +1,24 @@
#include <vector>
#include <cstdio>
/**
* 338. Counting Bits
* Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.
*/
class Solution {
public:
static std::vector<int> countBits(int n) {
std::vector<int> ans(n + 1);
for (int i = 0; i <= n; ++i)
ans[i] = __builtin_popcount(i);
return ans;
}
};
int main() {
auto ret = Solution::countBits(5);
for (int i : ret)
std::printf("%d ", i);
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220301-CN.cpp) ADD_EXECUTABLE(2203 220301.cpp)