Counting set bits
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Counting set bits means finding how many switches are on in a number. A neat trick removes exactly one lit bit per step, so the loop runs only as many times as there are lit bits. It is handy wherever bits record who or what is present.
Practical use cases
- Web app: Seats taken in a booking hall. A cinema booking page stores each row of seats as one number, with a lit bit per booked seat. Showing 12 seats booked in this row means counting lit bits. Counting them directly is faster than scanning all seats one by one for every row on every page view.
- Web app: How many permissions does this user have. A security audit page lists every user with the number of rights they hold. Rights live in one number, so counting lit bits gives the answer immediately. Admins quickly spot accounts holding far too many rights, and the page loads fast even with thousands of users listed.
- System: Image search and error detection. Similar-image search turns a picture into a bit pattern, then counts how many bits differ between two patterns to measure likeness. Network software also counts bits to check parity and detect transmission errors, which is how a corrupted download can be noticed before it reaches you.
The story: Diyas in the Dark
On Diwali night, Mira and Kabir lit a long row of diyas on the terrace wall, but the wind blew out many. Kabir wanted to know how many were still burning. "Walk along and count them all," he said, but the wall was long and most diyas were dark. Why waste time visiting every dark stand?
The computer version of this puzzle is "how many 1s are in the binary form of a number?", called the population count, or counting set bits. The slow way checks every bit: is the last bit 1? Shift right. Repeat. That takes as many steps as there are bits, lit or not.
Grandpa Bhaskar knew a better way. "Take the number and subtract one. Watch what happens: the lowest lit diya goes dark, and all the dark ones beneath it flip lit. Now keep only what both versions share (AND them). The lowest lit diya has vanished, and everything higher is untouched." One lit diya removed per step!
Repeat until the number reaches 0. The number of repeats equals the number of lit diyas. It is called Kernighan's algorithm, and it only runs as many times as there are set bits.
How to spot this problem, and where you need it
You store many yes or no values in one number and need to know how many are yes, or how different two such patterns are, without looping over every position.
Signs you need it
- The data is a bitmask of users, seats, features or flags and the question is how many are on.
- You need the distance between two bit patterns, which means counting the bits where they differ.
- A loop checks each of 32 or 64 positions even when only two or three bits are lit.
Where to use it in a project
- Dashboards reporting how many seats, slots, features or permissions are taken, from packed values.
- Duplicate or near-duplicate detection on compact fingerprints of images, files or text.
The solution
Use the clear-lowest-bit trick: a number AND the number minus one removes exactly the lowest lit bit. Repeat this and add one to a counter each time until the number reaches zero. The number of rounds equals the number of lit bits. To compare two patterns, XOR them first, and then count the lit bits of the result.
Payoff: Before: checking all 64 positions every time. After: only as many steps as there are lit bits, often 2 or 3.
Explain it like I am 8
Think of a row of candles, some lit. Instead of checking each stand, there is a neat trick that blows out exactly one lit candle every time you do it. Do it until no candle is lit, and the number of times you did it is your count.
How it works, step by step
- Start with n and a counter
count = 0. - While n is not 0, do
n = n & (n - 1). This erases the lowest set bit. - Count once each time you erase a bit.
- Stop when n becomes 0. The counter is the number of set bits.
- Know the alternative: check bit by bit with
n & 1andn >>= 1, which always takes as many steps as the number has bits.
The code in four languages
PHP
<?php
// Slow way: look at every bit.
function countSlow(int $n): int {
$count = 0;
while ($n > 0) {
$count += $n & 1; // is the last bit lit?
$n >>= 1; // slide to the next bit
}
return $count;
}
// Kernighan's way: each step erases the lowest lit bit.
function countFast(int $n): int {
$count = 0;
while ($n > 0) {
$n = $n & ($n - 1);
$count++;
}
return $count;
}
foreach ([0, 1, 7, 8, 180, 255, 1023] as $x) {
echo "$x (" . decbin($x) . "): " . countSlow($x) . " = " . countFast($x) . "
";
}JavaScript
// Slow way: look at every bit.
function countSlow(n) {
let count = 0;
while (n > 0) {
count += n & 1; // is the last bit lit?
n >>= 1; // slide to the next bit
}
return count;
}
// Kernighan's way: each step erases the lowest lit bit.
function countFast(n) {
let count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
for (const x of [0, 1, 7, 8, 180, 255, 1023]) {
console.log(x + " (" + x.toString(2) + "): " + countSlow(x) + " = " + countFast(x));
}Java
public class Main {
// Slow way: look at every bit.
static int countSlow(int n) {
int count = 0;
while (n > 0) {
count += n & 1; // is the last bit lit?
n >>= 1; // slide to the next bit
}
return count;
}
// Kernighan's way: each step erases the lowest lit bit.
static int countFast(int n) {
int count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}
return count;
}
public static void main(String[] args) {
for (int x : new int[]{0, 1, 7, 8, 180, 255, 1023}) {
System.out.println(x + " (" + Integer.toBinaryString(x) + "): " + countSlow(x) + " = " + countFast(x));
}
}
}Go
package main
import "fmt"
// countSlow looks at every bit.
func countSlow(n int) int {
count := 0
for n > 0 {
count += n & 1 // is the last bit lit?
n >>= 1 // slide to the next bit
}
return count
}
// countFast is Kernighan's way: each step erases the lowest lit bit.
func countFast(n int) int {
count := 0
for n > 0 {
n = n & (n - 1)
count++
}
return count
}
func main() {
for _, x := range []int{0, 1, 7, 8, 180, 255, 1023} {
fmt.Printf("%d (%b): %d = %d\n", x, x, countSlow(x), countFast(x))
}
}Time: O(k), where k is the number of set bits · Extra space: O(1). The loop runs once per lit bit, at most the number of bits in the number.
Watch out for
- Writing
n & (n + 1)instead ofn & (n - 1). - Using the loop on a negative number in a language with fixed-width integers, which has many set bits and may loop forever in shifts.
- Forgetting that the trick also checks powers of two:
n & (n - 1) === 0means exactly one bit (or none) is set.
Quick check
- How many set bits does 13 (1101) have?
- 2
- 3
- 4
- What does n & (n - 1) do?
- Clears the lowest set bit
- Doubles n
- Sets all bits
- How many loop rounds does Kernighan's method need for 1024 (only one bit set)?
- 10
- 1
- 1024