Print a number as string of ' A ' and ' B ' in lexicographic order | C ++ program to implement the above approach ; 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
#include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int no_of_characters ( int M ) { int k = 1 ; while ( true ) { if ( pow ( 2 , k + 1 ) - 2 < M ) k ++ ; else break ; } return k ; } void print_string ( int M ) { int 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 ) cout << " A " ; else { cout << " B " ; N -= num ; } k -- ; } cout << endl ; } int main ( ) { int M ; M = 30 ; print_string ( M ) ; M = 55 ; print_string ( M ) ; M = 100 ; print_string ( M ) ; return 0 ; }