File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments