Count Set Bits in C++
Count set bits in C++ three ways: a shift loop, Brian Kernighan's n & (n − 1) trick, and __builtin_popcount, with why negative numbers loop forever.
1#include <iostream>2#include <bitset>3using namespace std;45// Method 1: Using loop6int countSetBits1(int num) {7 int count = 0;8 while (num) {9 count += num & 1;10 num >>= 1;11 }12 return count;13}1415// Method 2: Using Brian Kernighan's algorithm16int countSetBits2(int num) {17 int count = 0;18 while (num) {19 num &= (num - 1); // Clears the rightmost set bit20 count++;21 }22 return count;23}2425// Method 3: Using built-in function (GCC)26int countSetBits3(int num) {27 return __builtin_popcount(num);28}2930int main() {31 int numbers[] = {12, 15, 255, 1024, 7};3233 cout << "Counting set bits:" << endl;34 for (int num : numbers) {35 cout << "\nNumber: " << bitset<16>(num) << " (" << num << ")" << endl;36 cout << "Method 1: " << countSetBits1(num) << " set bits" << endl;37 cout << "Method 2: " << countSetBits2(num) << " set bits" << endl;38 cout << "Method 3: " << countSetBits3(num) << " set bits" << endl;39 }4041 return 0;42}
Sample Output
Number: 0000010000000000 (1024)
A single 1 bit, so every method reports 1.
Method 2: 8 set bits
255 is 11111111.
In this one
- How to count bits with & 1 and >>
- Why n & (n − 1) clears the lowest set bit
- How __builtin_popcount and std::popcount work
- Why negative inputs need unsigned
How it works
- 1
For each of 12, 15, 255, 1024, and 7, print 16-bit binary.
- 2
Method 1: add num & 1, shift right, repeat.
- 3
Method 2: num &= num − 1, count, repeat.
- 4
Method 3: __builtin_popcount.
Dry run: Count Set Bits
Kernighan on 12:
- 1.1100 & 1011 = 1000 count 1
- 2.1000 & 0111 = 0000 count 2
- 3.Result 2
Kernighan on 12: 1100 & 1011 = 1000 count 1 1000 & 0111 = 0000 count 2 Result 2
Edge cases
Negative number
Add -1 to the array.
Method 1 never terminates, because right-shifting a negative int keeps filling in 1s. Use unsigned.
Zero
Add 0.
All three give 0; the loops never run.
MSVC
Compile with Visual C++.
__builtin_popcount is not defined. Use std::popcount (C++20) or __popcnt.
What's going on
Counting set bits means counting the 1s in a number's binary form; 12 (1100) has 2. This is also called the population count, or popcount. The program does it three ways and checks they agree.
Method 1 looks at every bit. num & 1 is the lowest bit, 0 or 1, and gets added to the count. num >>= 1 shifts everything right by one, dropping that bit. The loop runs until num is 0, so it takes as many passes as the position of the highest 1: 11 passes for 1024.
Method 2 is Brian Kernighan's trick. num & (num - 1) clears the lowest 1 bit. Subtracting 1 turns the lowest 1 into 0 and the 0s below it into 1s; ANDing with the original wipes all of those. So the loop runs once per 1 bit: just once for 1024 (10000000000), against 11 times for Method 1.
Method 3 is __builtin_popcount, a GCC and Clang built-in that usually compiles to a single CPU instruction. It does not exist in MSVC. In C++20 the portable version is std::popcount from <bit>, which needs an unsigned argument.
bitset<16>(num) prints each number as 16 binary digits so you can count the 1s by hand. 255 is eight 1s, and 7 is three.
Negative numbers break Method 1. A negative int shifted right keeps its sign bit, so num never reaches 0 and the loop runs forever. Passing the value as unsigned int fixes Methods 1 and 2.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <bitset> is there because it provides bitset for binary representation display. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Set Bits
Set Bit Concept:
Applications:
Method 1: Loop Through Bits
Algorithm:
int count = 0;
while (num) {
count += num & 1; // Check rightmost bit
num >>= 1; // Shift right
}
What happens here:
Time Complexity: O(total bits)
Method 2: Brian Kernighan's Algorithm
Algorithm:
int count = 0;
while (num) {
num &= (num - 1); // Clears rightmost set bit
count++;
}
What happens here:
Time Complexity: O(number of set bits)
Why Efficient:
Method 3: Built-in Function
Using __builtin_popcount():
int count = __builtin_popcount(num);
What happens here:
Note:
When to Use Each Method
Method 1 (Loop):
Method 2 (Brian Kernighan's):
Method 3 (Built-in):
Important Considerations
Efficiency:
Portability:
Edge Cases:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How many passes does Kernighan's loop make for 255?
Pick an answer to check it.
Question 2
What does 20 & 19 equal?
Pick an answer to check it.
Questions people ask
Which method is fastest?
The built-in, then Kernighan's, then the shift loop.
How do I count bits in a long long?
__builtin_popcountll or std::popcount on an unsigned long long.
Where is popcount used?
Hamming distance, bitmask DP, chess engines, and set sizes in bitsets.