Related Articles

# Replace array elements that contains K as a digit with the nearest power of K

• Last Updated : 28 Jun, 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.`

## Java

 `// Java program  for the above approach``import` `java.io.*;` `class` `GFG {``    ` `// Function to calculate the``// power of base nearest to x``static` `int` `nearestPow(``int` `x, ``int` `base1)``{``    ` `    ``// Stores logX to the base K``    ``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``));``}`` ` `// Function to replace array``// elements with nearest power of K``static` `void` `replaceWithNearestPowerOfK(``int` `[]arr, ``int` `K,``                                       ``int` `n)``{``    ` `    ``// Traverse the array``    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``        ` `        ``// Convert integer into a string``        ``int` `num = arr[i];``        ``String strEle = String.valueOf(num);`` ` `        ``for``(``int` `c = ``0``; c < strEle.length(); c++)``        ``{``            ` `            ``// If K is found, then replace``            ``// with the nearest power of K``            ``if` `((strEle.charAt(c) - ``'0'``) == K)``            ``{``                ``arr[i] = nearestPow(arr[i], K);``                ``break``;``            ``}``        ``}``    ``}``   ` `    ``// Print the array``    ``for``(``int` `i = ``0``; i < n; i++)``        ``System.out.print(arr[i] + ``" "``);``}` `// Driver Code``public` `static` `void` `main (String[] args)``{``    ` `    ``// Given array``    ``int` `[]arr = { ``432``, ``953``, ``232``, ``333` `};``    ``int` `n = arr.length;``    ` `    ``// 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 avanitrachhadiya2155`

## 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)`

## C#

 `// C# program  for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to calculate the``// power of base nearest to x``static` `int` `nearestPow(``int` `x, ``int` `base1)``{` `    ``// Stores logX to the base K``    ``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));``}` `// Function to replace array``// elements with nearest power of K``static` `void` `replaceWithNearestPowerOfK(``int` `[]arr, ``int` `K, ``int` `n)``{` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Convert integer into a string``        ``int` `num = arr[i];``        ``string` `strEle = num.ToString();` `        ``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++)``        ``Console.Write(arr[i]+``" "``);``}``// Driver Code``public` `static` `void` `Main()``{``  ` `    ``// Given array``    ``int` `[]arr = { 432, 953, 232, 333 };``    ``int` `n = arr.Length;` `    ``// 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 ipg2016107.`

## 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 DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up