Bit Counting Tricks
Implement three utilities on a non-negative 32-bit integer: count its 1 bits, decide whether it is a power of two, and isolate its lowest set bit. Each should run in time proportional to the number of set bits or better.
- 0 ≤ x < 2^32
x & (x − 1)clears the lowest set bit- A power of two has exactly one set bit
x & -xisolates the lowest set bit via two's complement
XOR cancels pairs, so "every element appears twice except one" is a single XOR pass with no extra memory. Sets of at most ~20 items fit in an integer bitmask, turning subset enumeration and "which nodes have been visited" states into cheap arithmetic that DP and BFS can index directly.
Popcount: loop x &= x - 1 until zero, counting iterations — each step removes one set bit. Power of two: x > 0 && (x & (x - 1)) == 0, because a single set bit becomes zero after one clear. Lowest set bit: x & -x, since negation flips all bits above the lowest set bit and keeps it. These identities underpin Fenwick trees and subset enumeration.
- Lookup tables per byte or the hardware
popcntinstruction give constant time. Iterating all 32 bits is simpler but slower.