Related Articles
Replace array elements that contains K as a digit with the nearest power of K
• Last Updated : 17 May, 2021

Given an array arr[] of size N and an integer K, the task is to replace every array element consisting of K as a digit, with its nearest power of K
Note: If there happen to be two nearest powers then take the greater one.

Examples:

Input: arr[] = {432, 953, 232, 333}, K = 3
Output: {243, 729, 243, 243}
Explanation:
arr = 35 = 243.
arr = 36 = 729.
arr = 35 = 243.
arr = 35 = 243.

Input: arr[] = {532, 124, 244, 485}, K = 4
Output: {532, 64, 256, 256}

Approach: The idea is to convert each element of the array into a string and then search for K in the string and if found then replace it with the nearest power of K. Follow the steps below to solve the problem:

• Declare a function to find the nearest power of K:
• Find the value of p for which Xp will be closest to the element.
• For calculating the p takes the floor value of logX(Element).
• Therefore, p and p+1 will be the two integers for which the nearest power can be obtained.
• Calculate Xk and X(K + 1) and check which is nearer to the element and return that element.
• Traverse the array arr[]:
• Convert each element into a string.
• Traverse the string and check for the presence of digit K and if found, then replace the array element with the nearest power of K and break from that point.
• Print the modified array.

Below is the implementation of the above approach:

## C++

 `// C++program  for the above approach``#include ``using` `namespace` `std;` `// Function to calculate the``// power of base nearest to x``int` `nearestPow(``int` `x, ``int` `base)``{` `    ``// Stores logX to the base K``    ``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));``}` `// Function to replace array``// elements with nearest power of K``void` `replaceWithNearestPowerOfK(``int` `arr[], ``int` `K, ``int` `n)``{` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Convert integer into a string``        ``string strEle = to_string(arr[i]);``      `  `        ``for` `(``int` `c = 0; c < strEle.length(); c++) {` `            ``// If K is found, then replace``            ``// with the nearest power of K``            ``if` `((strEle-``'0'``) == K) {``           ` `                ``arr[i] = nearestPow(arr[i], K);``                ``break``;``            ``}``        ``}``    ``}``  ` `    ``// Print the array``    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << arr[i] << ``" "``;``}``// Driver Code``int` `main()``{``  ` `    ``// Given array``    ``int` `arr[] = { 432, 953, 232, 333 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``// Given value of K``    ``int` `K = 3;` `    ``// Function call to replace array``    ``// elements with nearest power of K``    ``replaceWithNearestPowerOfK(arr, K, n);``}` `// This code is contributed by ukasp.`

## Python3

 `# Python3 program``# for the above approach``import` `math` `# Function to calculate the``# power of base nearest to x``def` `nearestPow(x, base):``  ` `    ``# Stores logX to the base K``    ``k ``=` `int``(math.log(x, base))` `    ``if` `abs``(base``*``*``k ``-` `x) < ``abs``(base``*``*``(k``+``1``) ``-` `x):``        ``return` `base``*``*``k``    ``else``:``        ``return` `base``*``*``(k``+``1``)` `# Function to replace array``# elements with nearest power of K``def` `replaceWithNearestPowerOfK(arr, K):` `    ``# Traverse the array``    ``for` `i ``in` `range``(``len``(arr)):` `        ``# Convert integer into a string``        ``strEle ``=` `str``(arr[i])` `        ``for` `c ``in` `strEle:` `            ``# If K is found, then replace``            ``# with the nearest power of K``            ``if` `int``(c) ``=``=` `K:``                ``arr[i] ``=` `nearestPow(arr[i], K)``                ``break``          ` `    ``# Print the array``    ``print``(arr)` `# Driver Code` `# Given array``arr ``=` `[``432``, ``953``, ``232``, ``333``]` `# Given value of K``K ``=` `3` `# Function call to replace array``# elements with nearest power of K``replaceWithNearestPowerOfK(arr, K)`

## Javascript

 ``
Output:
`[243, 729, 243, 243]`

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up