Menu
CoddyTech

Number of 1 Bits

You get a non-negative integer n. Write n in binary and return how many of its digits are 1. This count is also called the number of set bits, the population count or the Hamming weight. For example, 6 is 110 in binary, so it has two 1 bits.

Function

hammingWeight(n: integer) → integer
ninteger
a non-negative integer that fits in a signed 32-bit int
Returnsinteger
the number of 1 digits in the binary form of n

Constraints

  • 0 ≤ n ≤ 231-1

Examples

Input
n = 11
Output
3
Explanation
11 is 1011 in binary, which is 8 + 2 + 1. Three of its four binary digits are 1, so the answer is 3.
challenge icon

Follow-up

If this function ran millions of times, how could you count the bits of a 32-bit number with four lookups in a table of 256 precomputed counts?

Reset code
def hammingWeight(n):
    # Write code here

Test #1

Test #2

Test #3

Argument

n = 11

Expected Output

3