Count 1 bits in integers up to 53 bits without 32-bit ops
A permissions service stores each user’s feature flags as bits in one integer: bit 0 is “can export”, bit 1 is “can invite”, and so on. The admin page needs to show how many flags a user has turned on. There are more than 32 flags, so the integers can be larger than 32 bits.
Implement countSetBits(n). It returns the number of 1 bits in the binary representation of n.
countSetBits(n) // => number of 1 bits
n is a non-negative safe integer: from 0 up to Number.MAX_SAFE_INTEGER (253 − 1). -0 counts as 0.RangeError for anything else: negative numbers, fractions, NaN, Infinity, numbers above Number.MAX_SAFE_INTEGER, and non-numbers.&, |, >>, >>>) only work on 32 bits. Make sure bits above position 31 are counted too.n.toString(2)).countSetBits(0); // => 0
countSetBits(13); // => 3 (0b1101)
countSetBits(255); // => 8 (0b11111111)
countSetBits(2 ** 32); // => 1 (bit 32 only)
countSetBits(2 ** 32 + 6); // => 3
countSetBits(Number.MAX_SAFE_INTEGER); // => 53
countSetBits(-4); // throws RangeError
countSetBits(2.5); // throws RangeError