📜  通过将数字除以因子或从数组中删除数字的第一个出现,将数字转换为另一个数字

📅  最后修改于: 2021-05-13 23:36:07             🧑  作者: Mango

给定两个正整数AB和仅由数字[0-9 ]组成的数组D [] ,任务是检查是否有可能通过重复除以存在的任何因子来将A减少为B。数组d []或通过去除其任何数字第一次出现的,其存在于所述阵列d []。

例子:

方法:给定的问题可以通过使用队列,并检查是否在任何步骤A修改的到B或不是值上的值A执行所有可能的操作来解决。请按照以下步骤解决问题:

  • 初始化一个队列,例如Q,然后将A推入队列。
  • 初始化一个HashMap,比如说M以存储队列Q中存在的元素,并初始化一个变量ans“ No”以存储所需的结果。
  • 迭代直到Q不为空,然后执行以下步骤:
    • 将Q的前部存储在变量top中
    • 如果top的值等于B ,则将ans的值更新为“是”,然后退出循环。
    • 否则,遍历数组D [] ,对于每个元素, D [i]检查以下两个条件:
      • 如果d [i]顶部的一个因素,然后推动在队列Q除以顶部d [I]而得到的值的商和M中访问标记它。
      • 如果D [i]存在于数字top中,则删除其首次出现并推送在队列Q中获得的新数字,并在M中将其标记为已访问。
  • 完成上述步骤后,输出ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to check if a digit x is
// present in the number N or not
int isPresent(int n, int x)
{
    // Convert N to string
    string num = to_string(n);
 
    // Traverse the string num
    for (int i = 0; i < num.size();
         i++) {
 
        // Return first occurrence
        // of the digit x
        if ((num[i] - '0') == x)
            return i;
    }
    return -1;
}
 
// Function to remove the character
// at a given index from the number
int removeDigit(int n, int index)
{
    // Convert N to string
    string num = to_string(n);
 
    // Store the resultant string
    string ans = "";
 
    // Traverse the string num
    for (int i = 0;
         i < num.size(); i++) {
        if (i != index)
            ans += num[i];
    }
 
    // If the number becomes empty
    // after deletion, then return -1
    if (ans == "" || (ans.size() == 1
                      && ans[0] == '0'))
        return -1;
 
    // Return the number
    int x = stoi(ans);
    return x;
}
 
// Function to check if A can be
// reduced to B by performing the
// operations any number of times
bool reduceNtoX(int a, int b,
                int d[], int n)
{
    // Create a queue
    queue q;
 
    // Push A into the queue
    q.push(a);
 
    // Hashmap to check if the element
    // is present in the Queue or not
    unordered_map visited;
 
    // Set A as visited
    visited[a] = true;
 
    // Iterate while the queue is not empty
    while (!q.empty()) {
 
        // Store the front value of the
        // queue and pop it from it
        int top = q.front();
        q.pop();
 
        if (top < 0)
            continue;
 
        // If top is equal to B,
        // then return true
        if (top == b)
            return true;
 
        // Traverse the array, D[]
        for (int i = 0; i < n; i++) {
 
            // Divide top by D[i] if
            // it is possible and
            // push the result in q
            if (d[i] != 0 && top % d[i] == 0
                && !visited[top / d[i]]) {
 
                q.push(top / d[i]);
                visited[top / d[i]] = true;
            }
 
            // If D[i] is present at the top
            int index = isPresent(top, d[i]);
            if (index != -1) {
 
                // Remove the first occurrence
                // of D[i] from the top and
                // store the new number
                int newElement
                    = removeDigit(top, index);
 
                // Push newElement into the queue q
                if (newElement != -1
                    && (!visited[newElement])) {
                    q.push(newElement);
                    visited[newElement] = true;
                }
            }
        }
    }
 
    // Return false if A can
    // not be reduced to B
    return false;
}
 
// Driver Code
int main()
{
 
    int A = 5643, B = 81;
    int D[] = { 3, 8, 1 };
    int N = sizeof(D) / sizeof(D[0]);
 
    if (reduceNtoX(A, B, D, N))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Python3
# Python3 program for the above approach
from collections import deque
 
# Function to check if a digit x is
# present in the number N or not
def isPresent(n, x):
     
    # Convert N to string
    num = str(n)
 
    # Traverse the num
    for i in range(len(num)):
         
        # Return first occurrence
        # of the digit x
        if ((ord(num[i]) - ord('0')) == x):
            return i
             
    return -1
 
# Function to remove the character
# at a given index from the number
def removeDigit(n, index):
     
    # Convert N to string
    num = str(n)
 
    # Store the resultant string
    ans = ""
 
    # Traverse the num
    for i in range(len(num)):
        if (i != index):
            ans += num[i]
 
    # If the number becomes empty
    # after deletion, then return -1
    if (ans == "" or (len(ans) == 1 and
        ans[0] == '0')):
        return -1
 
    # Return the number
    x = int(ans)
    return x
 
# Function to check if A can be
# reduced to B by performing the
# operations any number of times
def reduceNtoX(a, b, d, n):
     
    # Create a queue
    q = deque()
 
    # Push A into the queue
    q.append(a)
 
    # Hashmap to check if the element
    # is present in the Queue or not
    visited = {}
 
    # Set A as visited
    visited[a] = True
 
    # Iterate while the queue is not empty
    while (len(q) > 0):
         
        # Store the front value of the
        # queue and pop it from it
        top = q.popleft()
 
        if (top < 0):
            continue
 
        # If top is equal to B,
        # then return true
        if (top == b):
            return True
 
        # Traverse the array, D[]
        for i in range(n):
             
            # Divide top by D[i] if
            # it is possible and
            # push the result in q
            if (d[i] != 0 and top % d[i] == 0 and
               (top // d[i] not in visited)):
                q.append(top // d[i])
                 visited[top // d[i]] = True
 
            # If D[i] is present at the top
            index = isPresent(top, d[i])
 
            if (index != -1):
 
                # Remove the first occurrence
                # of D[i] from the top and
                # store the new number
                newElement = removeDigit(top, index)
 
                # Push newElement into the queue q
                if (newElement != -1 and
                   (newElement not in  visited)):
                    q.append(newElement)
                    visited[newElement] = True
 
    # Return false if A can
    # not be reduced to B
    return False
 
# Driver Code
if __name__ == '__main__':
     
    A, B = 5643, 81
    D = [ 3, 8, 1 ]
    N = len(D)
     
    if (reduceNtoX(A, B, D, N)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to check if a digit x is
// present in the number N or not
static int isPresent(int n, int x)
{
    // Convert N to string
    string num = n.ToString();
 
    // Traverse the string num
    for (int i = 0; i < num.Length;
         i++) {
 
        // Return first occurrence
        // of the digit x
       if (((int)num[i] - 97) == x)
            return i;
    }
    return -1;
}
 
// Function to remove the character
// at a given index from the number
static int removeDigit(int n, int index)
{
    // Convert N to string
    string num = n.ToString();
 
    // Store the resultant string
    string ans = "";
 
    // Traverse the string num
    for (int i = 0;
         i < num.Length; i++) {
        if (i != index)
            ans += num[i];
    }
 
    // If the number becomes empty
    // after deletion, then return -1
    if (ans == "" || (ans.Length == 1
                      && ans[0] == '0'))
        return -1;
 
    // Return the number
    int x =  Int32.Parse(ans);;
    return x;
}
 
// Function to check if A can be
// reduced to B by performing the
// operations any number of times
static bool reduceNtoX(int a, int b,
                int []d, int n)
{
    // Create a queue
    Queue q = new Queue();
 
    // Push A into the queue
    q.Enqueue(a);
 
    // Hashmap to check if the element
    // is present in the Queue or not
    Dictionary visited = new Dictionary();
 
    // Set A as visited
    visited[a] = true;
 
    // Iterate while the queue is not empty
    while (q.Count>0) {
 
        // Store the front value of the
        // queue and pop it from it
        int top = q.Peek();
        q.Dequeue();
 
        if (top < 0)
            continue;
 
        // If top is equal to B,
        // then return true
        if (top == b)
            return true;
 
        // Traverse the array, D[]
        for (int i = 0; i < n; i++) {
 
            // Divide top by D[i] if
            // it is possible and
            // push the result in q
            if (d[i] != 0 && top % d[i] == 0 &&
                visited.ContainsKey(top / d[i]) && visited[top / d[i]]==false) {
 
                q.Enqueue(top / d[i]);
                   visited[top / d[i]] = true;
               
            }
 
            // If D[i] is present at the top
            int index = isPresent(top, d[i]);
            if (index != -1) {
 
                // Remove the first occurrence
                // of D[i] from the top and
                // store the new number
                int newElement = removeDigit(top, index);
 
                // Push newElement into the queue q
                if (newElement != -1 && (visited.ContainsKey(newElement) && visited[newElement]==false)) {
                    q.Enqueue(newElement);
                    
                        visited[newElement] = true;
                }
            }
        }
    }
 
    // Return false if A can
    // not be reduced to B
    return true;
}
 
// Driver Code
public static void Main()
{
 
    int A = 5643, B = 81;
    int []D = { 3, 8, 1 };
    int N = D.Length;
 
    if (reduceNtoX(A, B, D, N))
        Console.Write("Yes");
    else
        Console.Write("No");
 
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


输出:
Yes

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