Skip to content

Commit a50c105

Browse files
committed
feat(cpp): add hamming_weights_of_integers.cpp
1 parent 6c35816 commit a50c105

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#include <vector>
2+
3+
std::vector<int> hammingWeightsOfIntegers(int n) {
4+
std::vector<int> res;
5+
res.reserve(n + 1);
6+
for (int x = 0; x <= n; x++) {
7+
res.push_back(countSetBits(x));
8+
}
9+
return res;
10+
}
11+
12+
int countSetBits(int x) {
13+
int count = 0;
14+
// Count each set bit of 'x' until 'x' equals 0.
15+
while (x > 0) {
16+
// Increment the count if the LSB is 1.
17+
count += x & 1;
18+
// Right shift 'x' to shift the next bit to the LSB position.
19+
x >>= 1;
20+
}
21+
return count;
22+
}

0 commit comments

Comments
 (0)