Reduce the given Array of [ 1 , N ] by rotating left or right based on given conditions | C ++ program for the above approach ; Function to find the last element left after performing N - 1 queries of type X ; Stores the next power of 2 ; Iterate until nextPower is at most N ; If X is equal to 1 ; Stores the power of 2 less than or equal to N ; Return the final value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int rotate ( int arr [ ] , int N , int X ) { long long int nextPower = 1 ; while ( nextPower <= N ) nextPower *= 2 ; if ( X == 1 ) return nextPower - N ; long long int prevPower = nextPower / 2 ; return 2 * ( N - prevPower ) + 1 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int X = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << rotate ( arr , N , X ) ; return 0 ; }