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.
countSetBits(amount: int) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func countSetBits(amount int) int {
}
Worked examples
| Call | Result |
|---|---|
countSetBits(0) | 0 |
countSetBits(7) | 3 |
countSetBits(255) | 8 |
countSetBits(1024) | 1 |
Hint
Test the lowest bit, then shift right. Or the trick: n & (n - 1) clears exactly one set bit.
Reference solution in Go
func countSetBits(amount int) int {
if amount < 0 {
return -1
}
n, bits := amount, 0
for n > 0 {
n &= n - 1
bits++
}
return bits
}