DSAverse
Bit Manipulation
Loading Bit Manipulation...
Binary Register
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
bit 15bit 0
Initializing Sorting Algorithms...
Sorting
Trees
Graphs
Preparing interactive visualizations...
Bit Manipulation
Loading Bit Manipulation...
Binary Register
Brian Kernighan's algorithm counts 1-bits in O(set bits) time by repeatedly clearing the lowest set bit with n & (n−1).
Why does n & (n−1) always clear the lowest set bit of n?
Subtracting 1 flips the rightmost 1-bit to 0 and turns all trailing 0s to 1s. AND-ing with the original n zeroes out exactly that one set bit, leaving all higher bits untouched.