Same Number Of Set Bits As N | returns number of set bits in a number ; 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
function __builtin_popcount ( n ) { var d , t = 0 ; while ( n > 0 ) { d = n % 2 ; n = parseInt ( n / 2 ) ; if ( d == 1 ) t ++ ; } return t ; } function smallerNumsWithSameSetBits ( n ) { var temp = __builtin_popcount ( n ) ; var count = 0 ; for ( var i = n - 1 ; i > 0 ; i -- ) { if ( temp == __builtin_popcount ( i ) ) count ++ ; } return count ; } var n = 4 ; document . write ( smallerNumsWithSameSetBits ( n ) ) ;