Number from a range [ L , R ] having Kth minimum cost of conversion to 1 by given operations | Java implementation of the above approach ; Function to calculate the cost ; Base case ; Even condition ; Odd condition ; Return cost ; Function to find Kth element ; Array to store the costs ; Sort the array based on cost ; Driver code ; Given range and6 K ; Function call
import java . util . * ; class GFG { static int func ( int n ) { int count = 0 ; if ( n == 2 n == 1 ) return 1 ; if ( n % 2 == 0 ) count = 1 + func ( n / 2 ) ; if ( n % 2 != 0 ) count = 1 + func ( n * 3 + 1 ) ; return count ; } static void findKthElement ( int l , int r , int k ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; for ( int i = l ; i <= r ; i ++ ) arr . add ( i ) ; ArrayList < List < Integer > > result = new ArrayList < > ( ) ; for ( int i : arr ) result . add ( Arrays . asList ( i , func ( i ) ) ) ; Collections . sort ( result , ( s1 , s2 ) -> s1 . get ( 1 ) - s2 . get ( 1 ) ) ; System . out . println ( result . get ( k - 1 ) . get ( 0 ) ) ; } public static void main ( String [ ] args ) { int l = 12 ; int r = 15 ; int k = 2 ; findKthElement ( l , r , k ) ; } }