Skip to content

Commit 6c35816

Browse files
committed
feat(cpp): add hamming_weights_of_integers_dp.cpp
1 parent 079205d commit 6c35816

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include <vector>
2+
3+
std::vector<int> hammingWeightsOfIntegersDp(int n) {
4+
// Base case: the number of set bits in 0 is just 0.
5+
// We set dp[0] to 0 by initializing the entire DP array to 0.
6+
std::vector<int> dp(n + 1, 0);
7+
for (int x = 1; x <= n; x++) {
8+
// 'dp[x]' is obtained using the result of 'dp[x >> 1]', plus
9+
// the LSB of 'x'.
10+
dp[x] = dp[x >> 1] + (x & 1);
11+
}
12+
return dp;
13+
}

0 commit comments

Comments
 (0)