Drill

ProblemsJavaScript › warmup

Count the set bits

easywarmupJavaScript

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

countSetBits(amount: int) → int

Solve it in the editor →

Where you start

function countSetBits(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 JavaScript
function countSetBits(amount) {
  if (amount < 0) return -1;
  let n = amount, bits = 0;
  while (n > 0) { n &= n - 1; bits++; }
  return bits;
}

The same problem in another language

More warmup problems in JavaScript