Count Number of Set Bits / Hamming Weight

Implement countSetBits

Given a non-negative integer n, count how many bits in its binary representation are set to 1. Checking all 32 bit positions works but does the same amount of work regardless of how many bits are actually set. Brian Kernighan's trick skips straight past the zeros: n & (n - 1) always clears exactly the lowest set bit, so repeating that step counts down to zero in exactly as many steps as there are set bits — no wasted checks on positions that were already 0.

Example 1:

Input: n = 11

Output: 3

Example 2:

Input: n = 128

Output: 1

Example 3:

Input: n = 0

Output: 0

+ 9 hidden test cases run on Submit.

Constraints:

  • 0 ≤ n ≤ 2³¹ − 1

n =

11