Check if a number has same number of set and unset bits | Java 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
import java . io . * ; class GFG { static boolean checkSame ( int n ) { int set = 0 ; int unset = 0 ; while ( n > 0 ) { if ( ( n & 1 ) == 1 ) set ++ ; else unset ++ ; n = n >> 1 ; } if ( set == unset ) return true ; else return false ; } public static void main ( String [ ] args ) { int n = 12 ; if ( checkSame ( n ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }