How to count the total bits of a number that equal to one (1) in C++

2 Answers

0 votes
#include <iostream> 

using namespace std; 

void print_bits(int n) { 
    for (int i = 31; i >= 0; i--)
        cout << ((n >> i) & 1);
    cout << endl;
} 
   
unsigned int count_bits(unsigned int n) { 
    unsigned int count = 0; 
    while (n) { 
        count += n & 1; 
        n >>= 1; 
    } 
    return count; 
} 
  
int main() 
{ 
    int n = 1358; 
    
    print_bits(n);
    
    cout << count_bits(n); 
    
    return 0; 
}  


/*
run:

00000000000000000000010101001110
6

*/

 



answered Mar 5, 2019 by avibootz
0 votes
#include <iostream>
#include <bitset>
  
using namespace std;
  
int main() {
    unsigned int n = 1358;
    unsigned int counter;
    
    cout << bitset<16>(n) << endl;

    for (counter = 0; n; n >>= 1) {
      counter += n & 1;
    }
    
    cout << counter;
}


/*
run:
  
00001100
2
  
*/

 



answered Mar 27, 2019 by avibootz

Related questions

...