Welcome to collectivesolver - Programming & Software Q&A with code examples. A website you can trust. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Powerful WordPress hosting for WordPress professionals

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Aliexpress Today's Best Deals

Teach Your Child To Read

Disclosure: My content contains affiliate links.

28,263 questions

36,905 answers

573 users

How to count the number of 1 bit in a given number with C++

2 Answers

0 votes
#include <iostream>

int Count1Bit(int n) {
    int count = 0;
 
    while (n > 0) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

int main(void) {
    int n = 95; // 0101 1111
         
    int count = Count1Bit(n);
         
    std::cout << "Number of 1 bit = " << count;
    
    return 0;
}




/*
run:
       
Number of 1 bit = 6
       
*/

 


Protect Your Privacy - Download VPN


answered Sep 13, 2021 by avibootz
edited Dec 4, 2021 by avibootz
0 votes
#include <iostream>
 
int Count1Bit(int n) {
    int count = 0;
  
    while (n) {
        n &= (n - 1);
        count++;
    }
    
    return count;
}
 
int main(void) {
    int n = 95; // 0101 1111
          
    int count = Count1Bit(n);
          
    std::cout << "Number of 1 bit = " << count;
     
    return 0;
}
 
 
 
 
/*
run:
        
Number of 1 bit = 6
        
*/

 


Protect Your Privacy - Download VPN


answered May 14, 2022 by avibootz

Related questions

2 answers 33 views
1 answer 27 views
1 answer 29 views
...