Bit Manipulation
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Why Bits Now
Welcome to bit manipulation
You have already built a strong interview toolbox: arrays, linked lists, stacks, queues, trees, graphs, sorting, recursion, DP, greedy methods, hashing, advanced data structures, and string algorithms.
Now we zoom in even further: the individual bits inside an integer.
Bit manipulation matters because it helps you:
- Store many true/false states compactly
- Speed up set-like operations
- Recognize elegant interview tricks like XOR cancellation
- Solve subset, parity, permission, and low-level optimization problems
Think of this lesson as learning a new lens. Instead of asking, “What data structure should I use?” you’ll sometimes ask, “Can the data fit inside bits?”
We will stay practical and Java-focused.

Binary Mental Model
An integer is a row of switches
In decimal, each digit represents a power of 10.
In binary, each bit represents a power of 2:
bit index: 3 2 1 0
value: 8 4 2 1
bits: 1 0 1 0
So binary 1010 means:
1*8 + 0*4 + 1*2 + 0*1 = 10
In Java, an int has 32 bits. Most interview bit problems use non-negative integers, so you can usually reason with the rightmost bits first.
Important vocabulary:
- Least significant bit: rightmost bit
- Most significant bit: leftmost important bit
- Mask: a number used to target specific bits
-
Set bit: a bit equal to
1 -
Unset bit: a bit equal to
0

Java Bit Operators
The core operators
Java gives you several operators for working directly with bits:
Operator Meaning&
AND: bit is 1 only if both bits are 1
`
`
^
XOR: bit is 1 if bits are different
~
NOT: flips every bit
<<
left shift: move bits left, usually multiply by 2
>>
signed right shift
>>>
unsigned right shift
For interviews, &, |, ^, and << are the most common.
Run this Java example and connect the decimal output to the binary output.
```java
public class Main {
static String bits8(int x) {
return String.format("%8s", Integer.toBinaryString(x & 0xFF)).replace(' ', '0');
}
public static void main(String[] args) {
int a = 12; // 00001100
int b = 10; // 00001010
System.out.println("a = " + a + " " + bits8(a));
System.out.println("b = " + b + " " + bits8(b));
System.out.println("a & b = " + (a & b) + " " + bits8(a & b));
System.out.println("a | b = " + (a | b) + " " + bits8(a | b));
System.out.println("a ^ b = " + (a ^ b) + " " + bits8(a ^ b));
System.out.println("1 << 3 = " + (1 << 3) + " " + bits8(1 << 3));
}
}
```
Check A Bit
You have an integer n and a zero-based bit index k.
Which expression correctly checks whether the kth bit is set?
Masks As Sets
A mask can represent many booleans
Remember from Hashing that a HashSet can answer membership questions. A bitmask can do a similar job when the universe is small and indexable.
Example: suppose we track features:
bit 0 -> READ
bit 1 -> WRITE
bit 2 -> EXECUTE
Then one integer can store all enabled features:
permissions = 101₂
││└ READ enabled
│└─ WRITE disabled
└── EXECUTE enabled
Common mask operations:
Goal Expression Turn bitk on
`mask
Turn bit k off
mask & ~(1 << k)
Toggle bit k
mask ^ (1 << k)
Check bit k
(mask & (1 << k)) != 0
This is why bit manipulation often appears in subset problems, flags, permissions, and compact state representation.

Lowest Set Bit
Fill in the expression that removes the lowest set 1 bit from a positive integer n.
int result = ________;
Permission Mask Java
Bitmasks in real Java code
Let’s make the mask idea concrete with permissions.
Instead of storing three booleans, we store one integer:
-
READis bit0 -
WRITEis bit1 -
EXECUTEis bit2
This is not just a low-level trick. It is a compact way to represent a small set of options.
```java
public class Main {
public static void main(String[] args) {
int READ = 1 << 0; // 001
int WRITE = 1 << 1; // 010
int EXECUTE = 1 << 2; // 100
int permissions = 0;
// Turn on READ and EXECUTE
permissions = permissions | READ;
permissions = permissions | EXECUTE;
System.out.println("Can read? " + ((permissions & READ) != 0));
System.out.println("Can write? " + ((permissions & WRITE) != 0));
System.out.println("Can execute? " + ((permissions & EXECUTE) != 0));
// Toggle EXECUTE off
permissions = permissions ^ EXECUTE;
System.out.println("After toggle, can execute? " + ((permissions & EXECUTE) != 0));
}
}
```
XOR Cancellation
True or false?
For any integer x, the expression x ^ x equals 0.
Single Number Pattern
XOR is great for pairs
A classic MAANG-style warmup:
Every number appears exactly twice except one number that appears once. Find the single number.
You could use a HashMap from Hashing, but XOR gives a cleaner O(1) extra space solution.
Why?
a ^ a = 0
x ^ 0 = x
XOR order does not matter
So duplicate pairs cancel out, leaving only the unique value.
```java
public class Main {
public static int singleNumber(int[] nums) {
int ans = 0;
for (int num : nums) {
ans = ans ^ num;
}
return ans;
}
public static void main(String[] args) {
int[] nums = {4, 1, 2, 1, 2};
System.out.println("Single number: " + singleNumber(nums));
}
}
```
Interview Bit Playbook
How to recognize bit manipulation
Use bit manipulation when you see clues like:
- “Every element appears twice except one”
- “Count set bits”
- “Generate all subsets” with small
n - “Track used letters/options/states”
- “Check if a number is a power of two”
- “Store many flags compactly”
Common Java pitfalls
-
1 << kuses anint; for large shifts use1L << k -
>>preserves the sign bit;>>>shifts in zeros - Parentheses matter: write
(n & mask) != 0, notn & mask != 0 - Bit tricks are elegant, but explain them clearly in interviews
Your mental checklist
- Can each state be represented as yes/no?
- Can I map each state to a bit index?
- Do I need set, clear, toggle, or check?
- Is XOR cancellation useful?
- Are constraints small enough for a mask?
Next, we’ll briefly zoom out to problem difficulty itself with NP-completeness and approximation algorithms.
