Print N | Function to get the binary representation of the number N ; loop for each bit ; generate numbers in the range of ( 2 ^ N ) - 1 to 2 ^ ( N - 1 ) inclusive ; longest prefix check ; if counts of 1 is greater than counts of zero ; do sub - prefixes check ; Driver code ; Function call
function getBinaryRep ( N , num_of_bits ) { let r = " " ; num_of_bits -- ; while ( num_of_bits >= 0 ) { if ( ( N & ( 1 << num_of_bits ) ) != 0 ) r += " " ; else r += " " ; num_of_bits -- ; } return r ; } function NBitBinary ( N ) { let r = [ ] ; let first = 1 << ( N - 1 ) ; let last = first * 2 ; for ( let i = last - 1 ; i >= first ; -- i ) { let zero_cnt = 0 ; let one_cnt = 0 ; let t = i ; let num_of_bits = 0 ; while ( t > 0 ) { if ( ( t & 1 ) != 0 ) one_cnt ++ ; else zero_cnt ++ ; num_of_bits ++ ; t = t >> 1 ; } if ( one_cnt >= zero_cnt ) { let all_prefix_match = true ; let msk = ( 1 << num_of_bits ) - 2 ; let prefix_shift = 1 ; while ( msk > 0 ) { let prefix = ( msk & i ) >> prefix_shift ; let prefix_one_cnt = 0 ; let prefix_zero_cnt = 0 ; while ( prefix > 0 ) { if ( ( prefix & 1 ) != 0 ) prefix_one_cnt ++ ; else prefix_zero_cnt ++ ; prefix = prefix >> 1 ; } if ( prefix_zero_cnt > prefix_one_cnt ) { all_prefix_match = false ; break ; } prefix_shift ++ ; msk = msk & ( msk << 1 ) ; } if ( all_prefix_match ) { r . push ( getBinaryRep ( i , num_of_bits ) ) ; } } } return r ; } let n = 4 ; let results = NBitBinary ( n ) ; for ( let i = 0 ; i < results . length ; ++ i ) document . write ( results [ i ] + " " ) ; document . write ( " " ) ;