Bit Manipulation / UsageBit ChecksEasy

Bit Checks — Power of 2, Rightmost Bit, Parity

Common bit tricks: check power of 2, isolate rightmost set bit, check odd/even, count trailing zeros.

LC
Practice on LeetCode 231: Power of Two
Open Problem

Common Bit Checks

These one-liner tricks pop up everywhere in competitive programming and systems code. They all run in O(1) using bitwise operators.

The Tricks

Power of 2: n & (n-1) == 0
Odd/Even: n & 1
Rightmost set bit: n & (-n)
Clear lowest set: n & (n-1)
All bits set? n & (n+1) == 0

🔍 Live Bit Checker

C++ — Common Bit Checks
// Check if n is a power of 2
bool isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

// Check if n is odd
bool isOdd(int n) { return n & 1; }

// Isolate rightmost set bit
int rightmostBit(int n) { return n & (-n); }

// Clear the lowest set bit
int clearLowest(int n) { return n & (n - 1); }

// Count set bits
int popcount(int n) {
    int c = 0;
    while (n) { n &= n - 1; c++; }
    return c;
}
Complexity
Each Check
O(1)

Single bitwise operation.

Count Bits
O(K)

K = number of set bits.


📝 Notes

▼