beginner · bit manipulation · masks
Count the 1 bits
Problem
Return how many bits are 1 in the binary representation of a non-negative integer.
Constraints
- 0 ≤ x ≤ 65535 (16 bits shown)
Examples
x = 11 (1011₂) → 3
Show the solution
Kernighan's trick: x &= x − 1
Subtracting 1 flips the lowest 1 bit and every 0 below it; AND with the original keeps everything above and clears that bit.
Why it is correct
Each iteration clears exactly one 1 bit and no other, so the loop runs once per 1 bit.
Complexity
Time O(number of 1 bits) ≤ O(width), extra space O(1). One iteration per set bit.
For contrast: Test each of the 16 bits with a mask. That costs O(width) time and O(1) space.
Edge cases
- 0: no iterations.
- All 16 bits set: 16 iterations.
Common mistakes
- Right-shifting a negative signed value in languages with arithmetic shifts (the sign bit refills).
- Forgetting that many runtimes have a built-in (BitOperations.PopCount, Integer.bitCount, int.bit_count, std::popcount).
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class CountSetBits
{
/// <summary>Number of 1 bits in x (Kernighan). BitOperations.PopCount is the built-in. O(number of 1 bits).</summary>
public static int Count(uint x)
{
int count = 0;
while (x != 0)
{
x &= x - 1; // clears the lowest 1 bit
count++;
}
return count;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/CountSetBits.cs
def count(x: int) -> int:
"""Number of 1 bits in a non-negative x (Kernighan). int.bit_count() is the built-in. O(number of 1 bits)."""
result = 0
while x != 0:
x &= x - 1 # clears the lowest 1 bit
result += 1
return result
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/count_set_bits.py
package dev.bekadan.dsa.problems;
public final class CountSetBits {
private CountSetBits() {
}
/** Number of 1 bits in x (Kernighan). Integer.bitCount is the built-in. O(number of 1 bits). */
public static int count(int x) {
int count = 0;
while (x != 0) {
x &= x - 1; // clears the lowest 1 bit
count++;
}
return count;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/CountSetBits.java
#pragma once
namespace bekadan::dsa::problems {
// Number of 1 bits in x (Kernighan). std::popcount (C++20) is the built-in. O(number of 1 bits).
inline int count_set_bits(unsigned int x) {
int count = 0;
while (x != 0) {
x &= x - 1; // clears the lowest 1 bit
++count;
}
return count;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/count_set_bits.hpp