lowbit is n & -n
· algorithms
Flip the bits, add one, AND: the lowest set bit is n & -n.
Take a nonzero 32-bit int. From the low end, the first 1 together with the zeros below it is a power of two. That number is lowbit. For n = 0b110101000000, that is 0b000001000000.
First instinct
Walk bits until you find the 1.
int lowbit_naive(int n) { for (int k = 0; k <= 30; ++k) { if ((n & (1 << k)) > 0) { return 1 << k; } } return -1;}Flip, add one, AND
Then I flipped the word. The trailing zeros become ones; add one and they collapse back to zeros, and a one lands exactly where the original first 1 was. After that, n and ~n + 1 agree only on the lowbit — everything above it is opposite. Split as high bits / that 1 / the trailing zeros:
n 11010 1 000000~n 00101 0 111111~n + 1 00101 1 000000n & (~n+1) 00000 1 000000AND them together and you have it:
int lowbit_smart(int n) { return n & (~n + 1);}The pretty version
And ~n + 1 is just -n. So lowbit is n & -n.
int lowbit(int n) { return n & (-n);}