📌  相关文章
📜  通过删除或附加任何数字来最小化将 N 更改为 2 的幂的步骤

📅  最后修改于: 2022-05-13 01:56:07.268000             🧑  作者: Mango

通过删除或附加任何数字来最小化将 N 更改为 2 的幂的步骤

给定一个整数N ,任务是使用以下步骤找到将数字N更改为2的完美幂所需的最小步骤数:

  • 从数字中删除任何一位数字d
  • 在数字N的末尾添加任何数字d

例子:

方法:给定的问题可以使用贪心方法来解决,这个想法是存储所有 2 的幂且小于10 20的数字,并检查每个数字将给定数字转换为 20 的最小步骤2.按照以下步骤解决问题:

  • 初始化一个数组并存储所有2的幂且小于10 20的数字。
  • 将答案变量最好初始化为长度 + 1作为所需的最大步数。
  • 使用变量x遍历[0, len)范围,其中len是数组的长度,并执行以下步骤:
    • 初始化变量,例如position0
    • 迭代范围[0, len) ,其中len是使用变量i的数字的长度,如果位置小于len(x)并且x[position]等于num[i] ,则增加一个位置1
    • best的值更新为bestlen(x) + len(num) – 2*position的最小值。
  • 执行上述步骤后,打印best的值作为结果。

下面是上述方法的实现:

Java
// Java Program to implement
// the above approach
import java.util.*;
 
class GFG {
 
  // Function to find the minimum number of
  // steps required to reduce N to perfect
  // power of 2 by performing given steps
  static void findMinimumSteps(int N) {
    String num = String.valueOf(N);
    int c = 1;
 
    Stack a = new Stack<>();
 
    // Stores all the perfect power of 2
    while (true) {
      if (c > (int)Math.pow(10, 20)|| c>10 ) {
        break;
      }
      a.add(String.valueOf(c));
      c = c * 2;
    }
 
    // Maximum number of steps required
    int best = num.length()+1;
 
    // Iterate for each perfect power of 2
    String x;
    int i = 0;
    while (!a.isEmpty()) {
      x = a.pop();
      int position = 0;
 
      // Comparing with all numbers
      for (i = 0; i < num.length(); i++) {
 
        if (position < x.length() && x.charAt(position) == num.charAt(i))
          position += 1;
      }
 
      // Update the minimum number of
      // steps required
      best = (int) (Math.min(best, x.length() + num.length() - 2 * position));
 
    }
 
    // Print the result
    System.out.print(best-1);
 
  }
 
  // Driver Code
  public static void main(String[] args) {
    int N = 1092;
 
    // Function Call
    findMinimumSteps(N);
  }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python program for the above approach
 
# Function to find the minimum number of
# steps required to reduce N to perfect
# power of 2 by performing given steps
def findMinimumSteps(N):
 
    num = str(N)
    c = 1
    a = []
 
    # Stores all the perfect power of 2
    while True:
        if (c > 10 ** 20):
            break
        a.append(str(c))
        c = c * 2
 
    # Maximum number of steps required
    best = len(num) + 1
     
    # Iterate for each perfect power of 2
    for x in a:
        position = 0
         
        # Comparing with all numbers
        for i in range(len(num)):
           
            if position < len(x) and x[position] == num[i]:
                position += 1
                 
        # Update the minimum number of
        # steps required
        best = min(best, len(x) + len(num) - 2 * position)
         
    # Print the result
    print(best)
 
# Driver Code
N = 1092
 
# Function Call
findMinimumSteps(N)


Javascript


输出:
2

时间复杂度: O(N)
辅助空间: O(1)