Count Set Bits
Easy bit-manipulation
Description
Constraints
0 <= n <= 10^9
Examples
Input: n = 11
Output: 3
11 is 1011
Hints (1)
- n & (n - 1) clears the lowest set bit.
Solutions
Brian Kernighan bit trick. · Time O(bits) · Space O(1)
func countSetBits(n int) int {
count := 0
for n > 0 {
n &= n - 1
count++
}
return count
}
Brian Kernighan bit trick. · Time O(bits) · Space O(1)
function countSetBits(n) {
let count = 0;
while (n > 0) { n &= n - 1; count++; }
return count;
}
Brian Kernighan bit trick. · Time O(bits) · Space O(1)
function countSetBits($n) {
$count = 0;
while ($n > 0) { $n &= $n - 1; $count++; }
return $count;
}
Brian Kernighan bit trick. · Time O(bits) · Space O(1)
def countSetBits(n):
return bin(n).count("1")
Brian Kernighan bit trick. · Time O(bits) · Space O(1)
function countSetBits(n: number): number {
let count = 0;
while (n > 0) { n &= n - 1; count++; }
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account