Find iâ €™ th index character in a binary string obtained after n iterations | Set 2 | 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 program
function KthCharacter ( m , n , k ) { let distance = Math . pow ( 2 , n ) ; let Block_number = Math . floor ( k / distance ) ; let remaining = k % distance ; let s = new Array ( 32 ) . fill ( 0 ) ; let x = 0 ; for ( ; m > 0 ; x ++ ) { s [ x ] = m % 2 ; m = Math . floor ( m / 2 ) ; } let root = s [ x - 1 - Block_number ] ; if ( remaining == 0 ) { document . write ( root ) ; return ; } let flip = true ; while ( remaining > 1 ) { if ( ( remaining & 1 ) > 0 ) { flip = ! flip ; } remaining = remaining >> 1 ; } if ( flip ) { document . write ( ( root > 0 ) ? 0 : 1 ) ; } else { document . write ( root ) ; } } let m = 5 , k = 5 , n = 3 ; KthCharacter ( m , n , k ) ;