Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,821 answers

573 users

How to count the total zeros and ones in a binary number in C++

1 Answer

0 votes
#include <iostream>

#define INT_SIZE sizeof(int) * 8 
   
int main() {
    int number = 47079; // 1011011111100111
    int ones = 0, zeros = 0;
      
    for (int i = 0; i < INT_SIZE; i++) {
       if (number & 1) {
            ones++;
       }
        else {
            zeros++;
        }
 
        number >>= 1;
    }
   
    std::cout << ones << std::endl << zeros;
}
  
   
 
/*
run:
 
12
20
 
*/

 



answered Apr 1, 2019 by avibootz
edited Mar 31, 2024 by avibootz

Related questions

...