number-of-1-bits.sh — zsh
bit-manipulation

Given a non-negative integer n, return the number of set bits (1s) in its binary representation (also known as its Hamming weight).

Input / output

  • Input: n: int (0 <= n <= 2^31 - 1)
  • Output: int — count of 1 bits in n

Constraints

  • 0 <= n <= 2^31 - 1 (2147483647)

Follow-up

If hamming_weight is called millions of times in a tight loop, how can a small 256-entry byte lookup table answer each 32-bit query in 4 table lookups?

Examples
Example 1
Input: n = 11
Output: 3
Example 2: power of two
Input: n = 128
Output: 1
Example 3: near 31-bit max
Input: n = 2147483645
Output: 30