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 183 views
183 views asked May 8, 2019 by avibootz
1 answer 122 views
2 answers 164 views
2 answers 136 views
1 answer 118 views
1 answer 111 views
2 answers 125 views
...