Easy Bit Manipulation

Count Bits

Receives a non-negative integer n and returns the number of 1 bits (its population count, or Hamming weight) in n's binary representation. It applies Brian Kernighan's trick: repeatedly AND the running value with itself minus one, which clears exactly its current lowest set bit on every pass, so the loop runs once per set bit instead of once per bit position. Returns that count as a single integer — O(popcount) time, O(1) extra space; n ≤ 0 returns 0 directly, with no iterations.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References