Hamming Weight

easy · bit-manipulation, bit-count

Hamming Weight

Given a non-negative integer n, return the number of 1 bits in its binary representation.

Function signature

func HammingWeight(n uint32) int

Example

n = 11 (binary 1011)
output = 3

Constraints

  • 0 <= n <= 2^32 - 1

Notes

  • Clearing the lowest set bit repeatedly is an O(k) approach where k is the number of 1 bits.
Run tests to see results
No issues detected
    Join Discord