iq.lab
Python starts when a code cell comes near or you run one
easyBits and math target 15 min

Count the 1 bits

Given a whole number n from 0 to 232 - 1, return how many 1s appear when n is written in binary. This count is called the Hamming weight of n.

Binary is base 2: each digit, called a bit, is 0 or 1 and is worth a power of two, 1, 2, 4, 8 and so on from the right. 13 is 8 + 4 + 1, so it is 1101 in binary and its Hamming weight is 3.

bin(n).count("1") and n.bit_count() give the answer in one call and pass the tests. Practice the loop with bit operations instead: that loop is what this problem is for.

Example 1
Inputn = 13Output3

13 is 1101 in binary: three 1s.

Example 2
Inputn = 64Output1

64 is 26, which is 1000000 in binary: a 1 followed by six 0s.

Example 3
Inputn = 4294967295Output32

This is 232 - 1, the largest 32-bit number: all 32 bits are 1.

Constraints
  • 0 ≤ n ≤ 232 - 1 (n fits in 32 bits)

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.