Same Number Of Set Bits As N | Java program to find numbers less than N that have same Number Of Set Bits As N ;  ; function ; __builtin_popcount function that count set bits in n ; Iterate from n - 1 to 1 ; check if the number of set bits equals to temp increment count ; Driver Code
class GFG { static int __builtin_popcount ( int n ) { int d , t = 0 ; while ( n > 0 ) { d = n % 2 ; n = n / 2 ; if ( d == 1 ) t ++ ; } return t ; } static int smallerNumsWithSameSetBits ( int n ) { int temp = __builtin_popcount ( n ) ; int count = 0 ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( temp == __builtin_popcount ( i ) ) count ++ ; } return count ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( smallerNumsWithSameSetBits ( n ) ) ; } }