For an unsigned integer x, what does the expression x & (x - 1) do?
Correct answer
D. Clears the lowest set bit of x
13 views
D. Clears the lowest set bit of x
13 views
Subtracting one flips every bit from the lowest set bit downward, so ANDing with the original clears exactly that lowest 1 bit and leaves the higher bits intact. Repeating the operation counts set bits in Brian Kernighan's algorithm, and a single application tells you whether x is a power of two when the result is zero. The related expression x & -x isolates the lowest set bit instead of clearing it.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.