 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a number has same number of set and unset bits in C++
In this section we will check whether a number has same number of set bits and unset bits or not. Suppose the number 12 is there. Its binary representation is 1100. This has same number of 0s and 1s.
The approach is simple. We will check each bit of the number, and if that is 1, then increase set_bit_count, and if it is 0, then increase unset_bit_count. Finally, if they are same, then return true, otherwise false.
Example
#include <iostream> using namespace std; bool hasSameSetUnset(int n) {    int set_count = 0, unset_count = 0;    while(n){       if((n & 1) == 1){          set_count++;       }else{          unset_count++;       }       n = n >> 1; //shift to right    }    if(set_count == unset_count)    return true;    return false; } int main() {    int num = 35; //100011    if(hasSameSetUnset(num)){       cout << "Has same set, unset bits";    }else{       cout << "Not same number of set, unset bits";    } }  Output
Has same set, unset bits
Advertisements
 