Count the set bits
A permissions field packs flags into an integer, and the audit log reports how many are switched on.
- Only non-negative numbers have a meaningful flag count here.
- A negative input gives -1.
count_set_bits(amount: int) → int
Where you start
def count_set_bits(amount: int) -> int:
Worked examples
| Call | Result |
|---|---|
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