Bit Manipulation · Pattern 2 of 6
Bit tricks: lowest set bit, powers of two and repeating patterns
A handful of one-liners do most of the work: n & (n - 1) clears the lowest set bit, n & -n keeps only it, n | (n + 1) sets the lowest unset bit, and XOR of 1..n repeats every 4 numbers.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Count the set bits, or check for a power of two
- Do something with the lowest set or unset bit
- A formula for XOR of 1..n or a Gray code sequence
- Split a number or a range into powers of two
The template
int hammingWeight(int n) { // number of set bits
int count = 0;
for (; n != 0; n &= n - 1) count++; // each step clears the lowest 1
return count;
}
boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0; // exactly one set bit
}
int setRightmostUnset(int n) {
if ((n & (n + 1)) == 0) return n; // all ones already (like 111)
return n | (n + 1); // n + 1 flips the lowest 0 to 1
}
int xorUpTo(int n) { // 1 ^ 2 ^ ... ^ n
switch (n % 4) {
case 0: return n;
case 1: return 1;
case 2: return n + 1;
default: return 0;
}
}
int[] circularPermutation(int n, int start) { // Gray code, rotated to start
int[] res = new int[1 << n];
for (int i = 0; i < res.length; i++) res[i] = start ^ i ^ (i >> 1);
return res;
} def hamming_weight(n): # number of set bits, n >= 0
count = 0
while n:
n &= n - 1 # clears the lowest 1
count += 1
return count
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0 # exactly one set bit
def set_rightmost_unset(n):
if (n & (n + 1)) == 0: # all ones already (like 111)
return n
return n | (n + 1) # n + 1 flips the lowest 0 to 1
def xor_up_to(n): # 1 ^ 2 ^ ... ^ n
return [n, 1, n + 1, 0][n % 4]
def circular_permutation(n, start): # Gray code, rotated to start
return [start ^ i ^ (i >> 1) for i in range(1 << n)] int hammingWeight(uint32_t n) { // number of set bits
int count = 0;
for (; n != 0; n &= n - 1) count++; // each step clears the lowest 1
return count;
}
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0; // exactly one set bit
}
int setRightmostUnset(int n) {
if ((n & (n + 1)) == 0) return n; // all ones already (like 111)
return n | (n + 1); // n + 1 flips the lowest 0 to 1
}
int xorUpTo(int n) { // 1 ^ 2 ^ ... ^ n
int r[4] = {n, 1, n + 1, 0};
return r[n % 4];
}
vector<int> circularPermutation(int n, int start) { // Gray code, rotated to start
vector<int> res(1 << n);
for (int i = 0; i < (1 << n); i++) res[i] = start ^ i ^ (i >> 1);
return res;
} function hammingWeight(n) { // number of set bits
let count = 0;
for (; n !== 0; n &= n - 1) count++; // each step clears the lowest 1
return count;
}
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0; // exactly one set bit
}
function setRightmostUnset(n) {
if ((n & (n + 1)) === 0) return n; // all ones already (like 111)
return n | (n + 1); // n + 1 flips the lowest 0 to 1
}
function xorUpTo(n) { // 1 ^ 2 ^ ... ^ n
return [n, 1, n + 1, 0][n % 4];
}
function circularPermutation(n, start) { // Gray code, rotated to start
const res = [];
for (let i = 0; i < 1 << n; i++) res.push(start ^ i ^ (i >> 1));
return res;
} The variations
-
1The lowest set bit
n & (n - 1)removes the lowest 1, so a loop runs once per set bit, and a power of two is a number with nothing left after one step.n & -nisolates that bit; to reach 0 with the fewest ± powers of two, subtract a lone 1 but add to a run of 1s so it carries into one bit.Now you solve -
2The lowest unset bit and aligned blocks
n + 1turns the lowest 0 into 1 and clears the 1s below it; OR with n puts them back. The lowbitx & -xalso tells you the biggest aligned block starting at x, which is how a range of IP addresses splits into CIDR blocks.Now you solve- IP to CIDR Medium Stuck? solution
-
3Patterns that repeat
Write out a few values and look for the cycle. XOR of 1..n goes
n, 1, n + 1, 0with period 4. The Gray codei ^ (i >> 1)changes one bit per step, and XOR withstartrotates the cycle so it begins at start.Now you solve
Mistakes to avoid
isPowerOfTwowithoutn > 0: zero passes then & (n - 1)test, and in Java the most negative int does too.- Writing
n & n - 1 == 0: comparison binds tighter than&, so wrap it as(n & (n - 1)) == 0. - Counting bits of a negative number in Python with the
n & (n - 1)loop: it never ends. Mask with0xFFFFFFFFfirst.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.