How to count set bits of an integer in C++

1 Answer

0 votes
#include <iostream>
 
using namespace std;
 
unsigned int count_set_bits(unsigned int n) { 
    unsigned int count = 0; 
    while (n) { 
        count += n & 1; 
        n >>= 1; 
    } 
    return count; 
}  
 

int main() 
{ 
    int n = 45; //  00101101

    cout << count_set_bits(n); 
     
    return 0; 
} 
 
 
 
 
/*
run:
 
4
 
*/

 



answered May 8, 2019 by avibootz

Related questions

1 answer 182 views
182 views asked May 8, 2019 by avibootz
1 answer 116 views
2 answers 160 views
2 answers 134 views
1 answer 114 views
1 answer 108 views
2 answers 122 views
...