Find the n | Function to return the nth string in the required sequence ; Length of the resultant string ; Relative Index ; Initial string of length len consists of all a 's since the list is sorted ; Convert relative index to Binary form and set 0 = a and 1 = b ; Reverse and return the string ; Utility reverse function ; Driver code
function obtain_str ( n ) { let len = Math . floor ( ( Math . log ( n + 1 ) / Math . log ( 2 ) ) ) ; let rel_ind = n + 1 - Math . pow ( 2 , len ) ; let i = 0 ; let str = [ ] ; for ( i = 0 ; i < len ; i ++ ) { str . push ( ' ' ) ; } i = 0 ; while ( rel_ind > 0 ) { if ( rel_ind % 2 == 1 ) str [ i ] = ' ' ; rel_ind = parseInt ( rel_ind / 2 , 10 ) ; i ++ ; } return reverse ( str . join ( " " ) ) ; } function reverse ( input ) { let a = input . split ( ' ' ) ; let l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { let temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return a . join ( " " ) ; } let n = 11 ; document . write ( obtain_str ( n ) ) ;