Last Updated: December 9, 2025
Most developers avoid bit manipulation because it looks intimidating. Shifting bits, flipping 1s and 0s, reading cryptic expressions like n & (n - 1). It feels like black magic.
But here is the truth: bit manipulation is one of the highest ROI topics for coding interviews. A handful of techniques can solve dozens of problems, often in O(1) space and with blazing fast performance.
Computers think in bits. When you learn to think in bits too, you unlock solutions that would otherwise seem impossible.
In this chapter, we will cover:
Bit manipulation is the process of performing operations directly on the binary representation of numbers. Instead of working with decimal values, you work with individual bits (0s and 1s).
Every integer in a computer is stored as a sequence of bits. For example, the number 5 is stored as 101 in binary (assuming 3 bits for simplicity).
Before diving into techniques, you need to understand the six fundamental bitwise operators.
&)Returns 1 only if both bits are 1.
Use case: Check if a specific bit is set, clear bits, extract bits.
|)Returns 1 if at least one bit is 1.
Use case: Set specific bits to 1.
^)Returns 1 if the bits are different.
Use case: Toggle bits, find unique elements, swap values.
Key property: a ^ a = 0 and a ^ 0 = a
~)Flips all bits (0 becomes 1, 1 becomes 0).
Note: In most languages, ~n = -(n + 1) due to two's complement representation.
<<)Shifts bits to the left by specified positions. Each shift multiplies by 2.
Formula: n << k = n × 2^k
>>)Shifts bits to the right by specified positions. Each shift divides by 2 (integer division).
Formula: n >> k = n / 2^k (integer division)
Now let's look at the techniques that appear repeatedly in coding interviews.
To check if the k-th bit (0-indexed from right) is set to 1:
How it works:
1 << k creates a number with only the k-th bit setn & (1 << k) isolates that bitTo set the k-th bit to 1:
How it works: OR with a mask that has 1 at position k.
To clear (unset) the k-th bit:
How it works: AND with a mask that has 0 at position k and 1s everywhere else.
To flip a bit (0 to 1, or 1 to 0):
How it works: XOR with a mask that has 1 at position k.
A number is a power of 2 if it has exactly one bit set.
How it works:
Count the number of 1s in the binary representation:
Why it works: n & (n - 1) clears the rightmost set bit. We count how many times we can do this before n becomes 0.
Time complexity: O(number of set bits), not O(32)
Extract the rightmost bit that is set to 1:
How it works: In two's complement, -n = ~n + 1. This creates a number where only the rightmost set bit survives the AND.
This is the same trick used in counting set bits and checking power of 2.