diff --git a/java/Bit Manipulation/HammingWeightsOfIntegers.java b/java/Bit Manipulation/HammingWeightsOfIntegers.java new file mode 100644 index 0000000..4227434 --- /dev/null +++ b/java/Bit Manipulation/HammingWeightsOfIntegers.java @@ -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; + } +} diff --git a/java/Bit Manipulation/HammingWeightsOfIntegersDp.java b/java/Bit Manipulation/HammingWeightsOfIntegersDp.java new file mode 100644 index 0000000..63793d7 --- /dev/null +++ b/java/Bit Manipulation/HammingWeightsOfIntegersDp.java @@ -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; + } +} diff --git a/java/Bit Manipulation/LonelyInteger.java b/java/Bit Manipulation/LonelyInteger.java new file mode 100644 index 0000000..aa81f29 --- /dev/null +++ b/java/Bit Manipulation/LonelyInteger.java @@ -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; + } +} diff --git a/java/Bit Manipulation/SwapOddAndEvenBits.java b/java/Bit Manipulation/SwapOddAndEvenBits.java new file mode 100644 index 0000000..3530140 --- /dev/null +++ b/java/Bit Manipulation/SwapOddAndEvenBits.java @@ -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); + } +}