Skip to content

Commit b7edba6

Browse files
authored
Merge pull request ByteByteGoHq#51 from ongshunping/cpp-solutions-bit-manipulation
Add C++ solutions for Chapter 18 (Bit Manipulation)
2 parents c551142 + ccf624e commit b7edba6

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-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+
}
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+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include <vector>
2+
3+
int lonelyInteger(std::vector<int>& nums) {
4+
int res = 0;
5+
// XOR each element of the array so that duplicate values will
6+
// cancel each other out (x ^ x == 0).
7+
for (int i = 0; i < nums.size(); i++) {
8+
res ^= nums[i];
9+
}
10+
// 'res' will store the lonely integer because it would not have
11+
// been canceled out by any duplicate.
12+
return res;
13+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
unsigned int swapOddAndEvenBits(unsigned int n) {
2+
unsigned int evenMask = 0x55555555; // 01010101010101010101010101010101
3+
unsigned int oddMask = 0xAAAAAAAA; // 10101010101010101010101010101010
4+
unsigned int evenBits = n & evenMask;
5+
unsigned int oddBits = n & oddMask;
6+
// Shift the even bits to the left, the odd bits to the right, and
7+
// merge these shifted values together.
8+
return (evenBits << 1) | (oddBits >> 1);
9+
}

0 commit comments

Comments
 (0)