Code
Loading editor...
Tap Analyze to see visualization
Click Analyze to visualize
See step-by-step execution, variables, and output
Variables
Run code to see variables
Output
Console output will appear here
Click Analyze to visualize
See step-by-step execution, variables, and output
Run code to see variables
Console output will appear here
Use Brian Kernighan's algorithm: repeatedly clear the lowest set bit with n & (n - 1) and increment a counter. The loop runs exactly as many times as there are 1-bits.
Subtracting 1 flips all bits from the lowest set bit downward, so ANDing with the original clears exactly one set bit per iteration.
Updated Feb 2026