12 / 75
E

Number of 1 Bits

#12
bit-manipulation

Count the number of set bits (1s) in the binary representation of an integer.

Example:

Input:n = 11 (binary: 1011)
Output:3

Common Mistakes:

  • Using n % 2 and n /= 2 (less efficient)
  • Not handling unsigned integers correctly
  • Iterating all 32 bits instead of just set bits

Notes:

Brian Kernighan's algorithm: n & (n-1) removes the rightmost set bit. Time: O(number of 1s), not O(32).

12/75
Number of 1 Bits