Drill

ProblemsC# › warmup

Count the set bits

easywarmupBit manipulationMathC#

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

CountSetBits(amount: int) → int

C# 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.

Solve it in Python →

Where you start

public int CountSetBits(int amount) {
    
}

Worked examples

CallResult
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 C#
public int CountSetBits(int amount) {
    if (amount < 0) return -1;
    int n = amount, bits = 0;
    while (n > 0) { n &= n - 1; bits++; }
    return bits;
}

The same problem in another language

More warmup problems in C#