Skip to content

Java Chapter 18: Bit Manipulation #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions java/Bit Manipulation/HammingWeightsOfIntegers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
public class HammingWeightsOfIntegers {
public int[] hammingWeightsOfIntegers(int n) {
int[] res = new int[n + 1];
for (int x = 0; x < n + 1; x++) {
res[x] = countSetBits(x);
}
return res;
}

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