Number of 1 Bits

Problem Given an unsigned integer, count the number of set bits (1s) in its binary representation — the Hamming weight.

Input / Output

  • Input: a 32-bit unsigned integer n.
  • Output: the count of 1 bits.

Constraints

  • 32-bit unsigned input.
  • Aim for time proportional to the number of set bits rather than always 32 iterations.

Example

  • 11 (0b1011) → 3
  • 128 (0b1000_0000) → 1
  • 0 → 0
added …
LeaderboardSalaryAccount