Skip to content

Commit bf2407c

Browse files
authored
Merge pull request #73 from Jer3myYu/java-solutions-bit-manipulation
Java Chapter 18: Bit Manipulation
2 parents b683923 + 1c5fcfd commit bf2407c

File tree

4 files changed

+58
-0
lines changed

4 files changed

+58
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class HammingWeightsOfIntegers {
2+
public int[] hammingWeightsOfIntegers(int n) {
3+
int[] res = new int[n + 1];
4+
for (int x = 0; x < n + 1; x++) {
5+
res[x] = countSetBits(x);
6+
}
7+
return res;
8+
}
9+
10+
private int countSetBits(int x) {
11+
int count = 0;
12+
// Count each set bit of 'x' until 'x' equals 0.
13+
while (x > 0) {
14+
// Increment the count if the LSB is 1.
15+
count += x & 1;
16+
// Right shift 'x' to shift the next bit to the LSB position.
17+
x >>= 1;
18+
}
19+
return count;
20+
}
21+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class HammingWeightsOfIntegersDp {
2+
public int[] hammingWeightsOfIntegersDp(int n) {
3+
// Base case: the number of set bits in 0 is just 0. We set dp[0] to
4+
// 0 by initializing the entire DP array to 0.
5+
int[] dp = new int[n + 1];
6+
for (int x = 0; x < n + 1; x++) {
7+
// 'dp[x]' is obtained using the result of 'dp[x >> 1]', plus
8+
// the LSB of 'x'.
9+
dp[x] = dp[x >> 1] + (x & 1);
10+
}
11+
return dp;
12+
}
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class LonelyInteger {
2+
public int lonelyInteger(int[] nums) {
3+
int res = 0;
4+
// XOR each element of the array so that duplicate values will
5+
// cancel each other out (x ^ x == 0).
6+
for (int num : nums) {
7+
res ^= num;
8+
}
9+
// 'res' will store the lonely integer because it would not have
10+
// been canceled out by any duplicate.
11+
return res;
12+
}
13+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
public class SwapOddAndEvenBits {
2+
public int swapOddAndEvenBits(int n) {
3+
int evenMask = 0x55555555; // 01010101010101010101010101010101
4+
int oddMask = 0xAAAAAAAA; // 10101010101010101010101010101010
5+
int evenBits = n & evenMask;
6+
int oddBits = n & oddMask;
7+
// Shift the even bits to the left, the odd bits to the right, and
8+
// merge these shifted values together.
9+
return (evenBits << 1) | (oddBits >> 1);
10+
}
11+
}

0 commit comments

Comments
 (0)