Bit Tricks That Earn Their Keep
x & (x - 1), which clears the lowest set bit, and x & -x, which isolates it, built on the fact that subtracting 1 flips the lowest set bit and all the zeros below it.In short: subtracting 1 turns a number's trailing zeros into ones and clears its
lowest set bit, and that one fact powers a handful of O(1) one-liners: x & (x-1)
clears the lowest set bit, x & -x isolates it, and ~x & (x+1) isolates the lowest
zero bit instead. Clearing one set bit per pass (Kernighan's loop) counts the 1s in
O(popcount) time instead of O(width), which matters once a bitmap is mostly zeros.

Quarry stores records in fixed-size pages inside one big file, and it has to know which pages are free. Its answer is an allocation bitmap: one bit per page, 1 for used and 0 for free. A file with a million pages needs a bitmap of just 125 KB. But to allocate a page, Quarry has to find a 0 bit quickly, and to report usage it has to count the 1s. A loop over every bit can do both, but it's slow.
This lesson covers the handful of one-line tricks that make those questions cheap. Each works because of how subtracting 1, and negating in two's complement, change the lowest bits of a number. Once you see why, you won't need to memorise any of them.
What x - 1 does to the bits
Subtracting 1 borrows. Starting at bit 0, every trailing 0 becomes a 1 as the borrow passes through it, until the borrow reaches the lowest 1, which becomes 0. Above that, nothing changes:
x = 0 0 1 0 1 1 0 0 (44)
x - 1 = 0 0 1 0 1 0 1 1 (43)So x & (x - 1) keeps every bit above the lowest 1 and clears the lowest 1 and
everything below it. The net effect is that the lowest set bit is switched off.
print(40 & -40, 40 & 39)