Kth character from the Nth string obtained by the given operations | C ++ program for the above approach ; Function to return Kth character from recursive string ; If N is 1 then return A ; Iterate a loop and generate the recursive string ; Update current string ; Change A to B and B to A ; Reverse the previous string ; Return the kth character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char findKthChar ( int n , int k ) { string prev = " A " ; string cur = " " ; if ( n == 1 ) { return ' A ' ; } for ( int i = 2 ; i <= n ; i ++ ) { cur = prev + " B " ; for ( int i = 0 ; i < prev . length ( ) ; i ++ ) { if ( prev [ i ] == ' A ' ) { prev [ i ] = ' B ' ; } else { prev [ i ] = ' A ' ; } } reverse ( prev . begin ( ) , prev . end ( ) ) ; cur += prev ; prev = cur ; } return cur [ k - 1 ] ; } int main ( ) { int N = 4 ; int K = 3 ; cout << findKthChar ( N , K ) ; return 0 ; }