![]() |
VOOZH | about |
Given a number N, the task is to find the minimum number of operations to convert the given integer into any power of K where at each operation either any of the digits can be deleted or any of the digits can be appended at the back of the integer.
Examples:
Input: N = 247, K = 3
Output: 1
Explanation: In the 1st operation, digit 4 can be removed. Hence, N = 27 which is a power of K.Input: N = 5, K = 2
Output: 2
Explanation: In the 1st operation, digit 5 can be removed and in the 2nd operation, digit 2 can be appended in the end. Hence, N = 2 which is a power of K.
Approach: The given problem can be solved by storing all the powers of K in a vector and calculating the number of operations required to convert the given integer N into the current power. Below are the steps to follow:
Below is the implementation of the above approach:
1
Time Complexity: O((log N)2)
Auxiliary Space: O(1)