Find iâ €™ th index character in a binary string obtained after n iterations | Set 2 | C ++ program to find iaTMth Index character in a binary string obtained after n iterations ; Function to find the i - th character ; distance between two consecutive elements after N iterations ; binary representation of M ; kth digit will be derived from root for sure ; Check whether there is need to flip root or not ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void KthCharacter ( int m , int n , int k ) { int distance = pow ( 2 , n ) ; int Block_number = k / distance ; int remaining = k % distance ; int s [ 32 ] , x = 0 ; for ( ; m > 0 ; x ++ ) { s [ x ] = m % 2 ; m = m / 2 ; } int root = s [ x - 1 - Block_number ] ; if ( remaining == 0 ) { cout << root << endl ; return ; } bool flip = true ; while ( remaining > 1 ) { if ( remaining & 1 ) { flip = ! flip ; } remaining = remaining >> 1 ; } if ( flip ) { cout << ! root << endl ; } else { cout << root << endl ; } } int main ( ) { int m = 5 , k = 5 , n = 3 ; KthCharacter ( m , n , k ) ; return 0 ; }