Skip to content

Commit fbf5472

Browse files
Add Brian Kernighan's algorithm to count set bits by Abhijeet Kundu
1 parent b9c118f commit fbf5472

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// count_set_bits.cpp
2+
// Author: Abhijeet Kundu
3+
// Description: Counts number of set bits (1s) in the binary representation of an integer
4+
// using Brian Kernighan’s Algorithm.
5+
// Time Complexity: O(k) where k is number of set bits
6+
7+
#include <iostream>
8+
#include <cassert>
9+
10+
int countSetBits(int n) {
11+
int count = 0;
12+
while (n) {
13+
n &= (n - 1); // clears the least significant set bit
14+
count++;
15+
}
16+
return count;
17+
}
18+
19+
int main() {
20+
assert(countSetBits(0) == 0);
21+
assert(countSetBits(5) == 2); // 101 → 2 set bits
22+
assert(countSetBits(15) == 4); // 1111 → 4 set bits
23+
24+
int n;
25+
std::cout << "Enter a number: ";
26+
std::cin >> n;
27+
std::cout << "Number of set bits: " << countSetBits(n) << "\n";
28+
return 0;
29+
}

0 commit comments

Comments
 (0)