Print a number as string of ' A ' and ' B ' in lexicographic order | Function to calculate number of characters in corresponding string of ' A ' and ' B ' ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and ' B ' ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code
< ? php function no_of_characters ( $ M ) { $ k = 1 ; while ( true ) { if ( pow ( 2 , $ k + 1 ) - 2 < $ M ) $ k ++ ; else break ; } return $ k ; } function print_string ( $ M ) { $ k ; $ num ; $ N ; $ k = no_of_characters ( $ M ) ; $ N = $ M - ( pow ( 2 , $ k ) - 2 ) ; while ( $ k > 0 ) { $ num = pow ( 2 , $ k - 1 ) ; if ( $ num >= $ N ) echo " A " ; else { echo " B " ; $ N -= $ num ; } $ k -- ; } echo " STRNEWLINE " ; } $ M ; $ M = 30 ; print_string ( $ M ) ; $ M = 55 ; print_string ( $ M ) ; $ M = 100 ; print_string ( $ M ) ; ? >