Replace array elements that contains K as a digit with the nearest power of K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nearestPow ( int x , int base ) { int k = int ( log ( x ) / log ( base ) ) ; if ( abs ( pow ( base , k ) - x ) < abs ( pow ( base , ( k + 1 ) ) - x ) ) return pow ( base , k ) ; else return pow ( base , ( k + 1 ) ) ; } void replaceWithNearestPowerOfK ( int arr [ ] , int K , int n ) { for ( int i = 0 ; i < n ; i ++ ) { string strEle = to_string ( arr [ i ] ) ; for ( int c = 0 ; c < strEle . length ( ) ; c ++ ) { if ( ( strEle - '0' ) == K ) { arr [ i ] = nearestPow ( arr [ i ] , K ) ; break ; } } } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 432 , 953 , 232 , 333 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; replaceWithNearestPowerOfK ( arr , K , n ) ; }