Value of k | CPP program to fin k - th element after append and insert middle operations ; int ans = n ; Middle element of the sequence ; length of the resulting sequence . ; Updating the middle element of next sequence ; Moving to the left side of the middle element . ; Moving to the right side of the middle element . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findElement ( int n , int k ) { int left = 1 ; int right = pow ( 2 , n ) - 1 ; while ( 1 ) { int mid = ( left + right ) / 2 ; if ( k == mid ) { cout << ans << endl ; break ; } ans -- ; if ( k < mid ) right = mid - 1 ; else left = mid + 1 ; } } int main ( ) { int n = 4 , k = 8 ; findElement ( n , k ) ; return 0 ; }