Replace array elements that contains K as a digit with the nearest power of K | Java program for the above approach ; Function to calculate the power of base nearest to x ; Stores logX to the base K ; Function to replace array elements with nearest power of K ; Traverse the array ; Convert integer into a string ; If K is found , then replace with the nearest power of K ; Print the array ; Driver Code ; Given array ; Given value of K ; Function call to replace array elements with nearest power of K
import java . io . * ; class GFG { static int nearestPow ( int x , int base1 ) { int k = ( int ) ( Math . log ( x ) / Math . log ( base1 ) ) ; if ( Math . abs ( Math . pow ( base1 , k ) - x ) < Math . abs ( Math . pow ( base1 , ( k + 1 ) ) - x ) ) return ( int ) Math . pow ( base1 , k ) ; else return ( int ) Math . pow ( base1 , ( k + 1 ) ) ; } static void replaceWithNearestPowerOfK ( int [ ] arr , int K , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int num = arr [ i ] ; String strEle = String . valueOf ( num ) ; for ( int c = 0 ; c < strEle . length ( ) ; c ++ ) { if ( ( strEle . charAt ( c ) - '0' ) == K ) { arr [ i ] = nearestPow ( arr [ i ] , K ) ; break ; } } } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 432 , 953 , 232 , 333 } ; int n = arr . length ; int K = 3 ; replaceWithNearestPowerOfK ( arr , K , n ) ; } }