DSA — Bit Manipulation
Bitwise Operators
| Operator | Name | Example |
|---|---|---|
| & | AND | 5 & 3 = 1 |
| | | OR | 5 | 3 = 7 |
| ^ | XOR | 5 ^ 3 = 6 |
| ~ | NOT | ~5 = -6 |
| << | Left shift | 5 << 1 = 10 |
| >> | Right shift | 5 >> 1 = 2 |
Common Operations
# Check if power of 2
def is_power_of_2(n):
return n > 0 and (n & (n - 1)) == 0
# Get ith bit
def get_bit(num, i):
return (num >> i) & 1
# Set ith bit
def set_bit(num, i):
return num | (1 << i)
# Clear ith bit
def clear_bit(num, i):
return num & ~(1 << i)
# Count set bits
def count_bits(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
XOR Tricks
# Find unique element (all others appear twice)
def find_unique(arr):
result = 0
for num in arr:
result ^= num
return result
# Swap without temp
a, b = a ^ b, a ^ b, a ^ b
Mini Practice
- Check power of 2
- Count set bits
- Find unique element
- Swap without temp variable
Up Next
Continue with Trie — prefix tree data structure.
Related Topics
Frequently Asked Questions about Bit Manipulation
What is Bit Manipulation in DSA?
Bit Manipulation is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Bit Manipulation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Bit Manipulation.
Why is Bit Manipulation important in DSA?
Bit Manipulation is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.