C Program to Count Set Bits in an Integer
n & 1 to check the last bit and n >>= 1 to shift bits right, incrementing a counter for each set bit.Examples
How to Think About It
AND with 1. If it is 1, increase the count. Then move to the next bit by shifting the number right by one. Repeat until the number becomes zero.Algorithm
Code
#include <stdio.h> int countSetBits(int n) { int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } int main() { int num = 5; printf("Number of set bits in %d is %d\n", num, countSetBits(num)); 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: Count increment
If the last bit is 1, we add 1 to the count to keep track of set bits.
Step 3: Shift bits
Right shifting n >>= 1 moves to the next bit by discarding the last bit already counted.
Alternative Approaches
#include <stdio.h> int countSetBits(int n) { int count = 0; while (n) { n &= (n - 1); count++; } return count; } int main() { int num = 5; printf("Number of set bits in %d is %d\n", num, countSetBits(num)); return 0; }
#include <stdio.h> int main() { int num = 5; int count = __builtin_popcount(num); printf("Number of set bits in %d is %d\n", num, count); return 0; }
Complexity: O(k) time, O(1) space
Time Complexity
The loop runs once for each bit in the integer (usually 32 or 64), so it is O(k) where k is the number of bits.
Space Complexity
Only a few variables are used, so space complexity is O(1), constant space.
Which Approach is Fastest?
Brian Kernighan's algorithm is faster when the number has fewer set bits because it loops only as many times as there are set bits.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bitwise check each bit | O(k) | O(1) | Simple and clear for beginners |
| Brian Kernighan's Algorithm | O(m) where m = set bits | O(1) | Faster for sparse set bits |
| Built-in function (__builtin_popcount) | O(1) | O(1) | Fastest but compiler-dependent |