Examples of Bit Manipulation
How to check if a number is power of 2 ?
- Naive way is to keep dividing it by if it is even and if we end up with it is power of otherwise it's not.
demo.java
boolean isPowerOfTwo(int n) {
if(n == 0)
return false;
else {
while(n % 2 == 0) n /= 2;
return (n == 1);
}
}
Time complexity of the above code is .
- Here is a clever trick to solve it in constant time .
- Consider a number which is power of which means for some
It is obvious that will have only bit equal to , all the remaining bits will be - Now think about , it will be have bit equal to if .
- In simpler words will have all the bits as 1 after bit.
- Consider
- This can be generalized to any which is power of i.e
- Consider a number which is power of which means for some
demo.java
boolean isPowerOfTwo(int n) {
if(n == 0)
return false;
return (n & (n - 1)) == 0
}
How to check if certain bit at position is set in a number
We can use combination of Logical AND and Left shift operator <<
Notice that can be written as and if bit of is then
demo.java
boolean checkIfIthBitIsSet(int n, int i) {
return ((n & (1 << i)) != 0);
}
Generate all possible subsets of a set
We can use bitmasking to solve this problem.
Consider a set of three elements. We can iterate over all possible binary masks of length
We will be picking element from original set if current bit mask has bit set.
demo.java
// Function to generate all possible subsets using bit manipulation
public static List<List<Integer>> generateSubsets(int[] set) {
List<List<Integer>> result = new ArrayList<>();
int n = set.length;
// There are 2^n subsets for a set of size n
for (int i = 0; i < (1 << n); i++) { // Loop through all 2^n possible subsets
List<Integer> subset = new ArrayList<>();
for (int j = 0; j < n; j++) {
// Check if the j-th bit of i is set (1)
if ((i & (1 << j)) != 0) {
subset.add(set[j]);
}
}
result.add(subset);
}
return result;
}
Few more tricks with bit manipulation
- Return rightmost bit or in
- Set bit to in
- Toggle bit in
- Count set bits in a integer
demo.java
// Number of iterations in this loop is equal to number of set bits
public static int countSetBits(int x) {
int count = 0;
while (x > 0) {
count += 1;
x &= (x - 1);
}
return count;
}
-
Swapping two numbers without temporary variable
-
Rotate bits by number of bit positions
- Left Rotate
- Right Rotate
-
Unique element in the array : If all the integers appear twice except for one integer, we can
XOR
all the integers to get unique integer
Practical Applications
- Efficient Storage:
- Use bits to represent flags or states compactly (e.g., feature toggles, permissions).
- Boolean Matrix Operations
- Represent rows/columns as bitmasks for fast bitwise operations.
- Dynamic Programming with BitMasking
- Solve combinatorial problems efficiently, such as
traveling salesman
,subset-sum
, etc.
- Solve combinatorial problems efficiently, such as
- Optimize Arithmetic Operations
- Use shifts for multiplication/division by powers of two.
- Hashing