Check if a number has same number of set and unset bits | C ++ program to check if a number has same number of set and unset bits ; Function to check if a number has same setbits and unset bits ; iterate for all bits of a number ; if set ; if unset ; right shift number by 1 ; is number of set bits are equal to unset bits ; Driver Code ; function to check
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSame ( int n ) { int set = 0 , unset = 0 ; while ( n ) { if ( n & 1 ) set ++ ; else unset ++ ; n = n >> 1 ; } if ( set == unset ) return true ; else return false ; } int main ( ) { int n = 12 ; if ( checkSame ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }