DevPath

← All problems

Count Set Bits

Easy bit-manipulation

Description

Return the number of 1 bits in the binary representation of a non-negative integer.

Constraints

0 <= n <= 10^9

Examples

Input: n = 11

Output: 3

11 is 1011

Hints (1)
  • n & (n - 1) clears the lowest set bit.

Solutions

Brian Kernighan bit trick. · Time O(bits) · Space O(1)

func countSetBits(n int) int {
    count := 0
    for n > 0 {
        n &= n - 1
        count++
    }
    return count
}

Create a free account to submit solutions, track progress and save problems.

Create account