Count the number of binary 1 flags for a given positive integer. For instance:
1 = 0b1 => 1 bit 2 = 0b10 => 1 bit 3 = 0b11 => 2 bits
Recursively
func countBitsRec(var n: NSInteger) -> NSInteger {
return n == 0 ? 0 : n & 1 + countBits(n >> 1)
}
countBitsRec(1898)
Iteratively
func countBits(var n: NSInteger) -> NSInteger {
var numberOfBits = 0
while n != 0 {
if n & 1 == 1 {
numberOfBits++;
}
numberOfBits
n >>= 1
}
return numberOfBits
}
countBits(1)