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 258 views
258 views asked May 8, 2019 by avibootz
1 answer 203 views
2 answers 270 views
2 answers 236 views
1 answer 196 views
1 answer 194 views
2 answers 224 views
...