Drill

ProblemsPython › warmup

Count the set bits

easywarmupPython

A permissions field packs flags into an integer, and the audit log reports how many are switched on.

count_set_bits(amount: int) → int

Solve it in the editor →

Where you start

def count_set_bits(amount: int) -> int:
    

Worked examples

CallResult
count_set_bits(0)0
count_set_bits(7)3
count_set_bits(255)8
count_set_bits(1024)1

Hint

Test the lowest bit, then shift right. Or the trick: n & (n - 1) clears exactly one set bit.

Reference solution in Python
def count_set_bits(amount: int) -> int:
    if amount < 0:
        return -1
    n, bits = amount, 0
    while n:
        n &= n - 1
        bits += 1
    return bits

The same problem in another language

More warmup problems in Python