Reduce the given Array of [ 1 , N ] by rotating left or right based on given conditions | Java 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
import java . io . * ; class GFG { static int rotate ( int arr [ ] , int N , int X ) { long nextPower = 1 ; while ( nextPower <= N ) nextPower *= 2 ; if ( X == 1 ) return ( int ) nextPower - N ; long prevPower = nextPower / 2 ; return 2 * ( N - ( int ) prevPower ) + 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int X = 1 ; int N = arr . length ; System . out . println ( rotate ( arr , N , X ) ) ; } }