</>
Skip to content
DSA lessons (52/55)

DSA — Bit Manipulation

Bitwise Operators

OperatorNameExample
&AND5 & 3 = 1
|OR5 | 3 = 7
^XOR5 ^ 3 = 6
~NOT~5 = -6
<<Left shift5 << 1 = 10
>>Right shift5 >> 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

  1. Check power of 2
  2. Count set bits
  3. Find unique element
  4. 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.