C++ Program to Count Set Bits in an Integer
n & 1 to check the last bit and n >>= 1 to shift bits right, like this: int count = 0; while(n) { count += n & 1; n >>= 1; }.Examples
How to Think About It
AND with 1. If it is 1, increase the count. Then shift the number right by one bit to check the next bit. Repeat until the number becomes zero.Algorithm
Code
#include <iostream> using namespace std; int countSetBits(int n) { int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } int main() { int num = 5; cout << "Number of set bits in " << num << " is " << countSetBits(num) << endl; return 0; }
Dry Run
Let's trace the number 5 through the code to count set bits.
Initial value
n = 5 (binary 0101), count = 0
Check last bit
5 & 1 = 1, so count = 1
Shift right
n >>= 1 -> n = 2 (binary 0010)
Check last bit
2 & 1 = 0, count stays 1
Shift right
n >>= 1 -> n = 1 (binary 0001)
Check last bit
1 & 1 = 1, count = 2
Shift right
n >>= 1 -> n = 0, loop ends
| n (decimal) | n (binary) | n & 1 | count |
|---|---|---|---|
| 5 | 0101 | 1 | 1 |
| 2 | 0010 | 0 | 1 |
| 1 | 0001 | 1 | 2 |
Why This Works
Step 1: Check last bit
Using n & 1 isolates the last bit of the number to see if it is set (1).
Step 2: Increment count
If the last bit is 1, we add 1 to the count to keep track of set bits.
Step 3: Shift bits right
Shifting the number right by one bit with n >>= 1 moves the next bit into the last bit position for checking.
Step 4: Repeat until zero
We repeat this process until all bits are checked and the number becomes zero.
Alternative Approaches
#include <iostream> using namespace std; int countSetBits(int n) { int count = 0; while (n) { n &= (n - 1); count++; } return count; } int main() { int num = 5; cout << "Number of set bits in " << num << " is " << countSetBits(num) << endl; return 0; }
#include <iostream> #include <bitset> using namespace std; int main() { int num = 5; bitset<32> b(num); cout << "Number of set bits in " << num << " is " << b.count() << endl; return 0; }
Complexity: O(k) time, O(1) space
Time Complexity
The loop runs once for each bit in the number (k bits), so time is O(k).
Space Complexity
Only a few variables are used, so space is O(1).
Which Approach is Fastest?
Brian Kernighan's method is faster because it loops only as many times as there are set bits, not all bits.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple bitwise loop | O(k) | O(1) | Easy to understand, small code |
| Brian Kernighan's Algorithm | O(m) where m = set bits | O(1) | Performance critical code |
| std::bitset | O(k) | O(k) | Quick coding with standard library |