Проверить, может ли N быть представлено в виде суммы натуральных чисел, содержащих цифру D хотя бы один раз.
Опубликовано: 22 Сентября, 2022
Даны натуральное число N и цифра D , задача состоит в том, чтобы проверить, может ли N быть представлено в виде суммы натуральных чисел, содержащих цифру D хотя бы один раз. Если можно представить N в таком формате, то выведите «Да» . В противном случае выведите «Нет» .
Примеры:
Input: N = 24, D = 7
Output: Yes
Explanation: The value 24 can be represented as 17 + 7, both containing the digit 7.Input: N = 27 D = 2
Output: Yes
Подход: выполните шаги, чтобы решить проблему:
- Проверьте, содержит ли данное N цифру D или нет. Если найдено верно , то выведите «Да» .
- В противном случае повторяйте, пока N не станет больше 0 , и выполните следующие шаги:
- Вычитание значения D из значения N .
- Проверьте, содержит ли обновленное значение N цифру D или нет. Если окажется, что это правда , то выведите «Да» и прервите цикл.
- После выполнения вышеуказанных шагов, если ни одно из вышеперечисленных условий не удовлетворяет, то выведите «Нет» .
Ниже приведена реализация вышеуказанного подхода:
C++
// C++ program for the above approach#include <iostream>using namespace std;// Function to check if N contains// digit D in itbool findDigit(int N, int D){ // Iterate until N is positive while (N > 0) { // Find the last digit int a = N % 10; // If the last digit is the // same as digit D if (a == D) { return true; } N /= 10; } // Return false return false;}// Function to check if the value of// N can be represented as sum of// integers having digit d in itbool check(int N, int D){ // Iterate until N is positive while (N > 0) { // Check if N contains digit // D or not if (findDigit(N, D) == true) { return true; } // Subtracting D from N N -= D; } // Return false return false;}// Driver Codeint main(){ int N = 24; int D = 7; if (check(N, D)) { cout << "Yes"; } else { cout << "No"; } return 0;} |
Java
// Java approach for the above approachimport java.util.*;class GFG{// Function to check if N contains// digit D in itstatic boolean findDigit(int N, int D){ // Iterate until N is positive while (N > 0) { // Find the last digit int a = N % 10; // If the last digit is the // same as digit D if (a == D) { return true; } N /= 10; } // Return false return false;}// Function to check if the value of// N can be represented as sum of// integers having digit d in itstatic boolean check(int N, int D){ // Iterate until N is positive while (N > 0) { // Check if N contains digit // D or not if (findDigit(N, D) == true) { return true; } // Subtracting D from N N -= D; } // Return false return false;} // Driver Codepublic static void main(String[] args){ int N = 24; int D = 7; if (check(N, D)) { System.out.print("Yes"); } else { System.out.print("No"); }}}// This code is contributed by sanjoy_62 |
Python3
# Python3 program for the above approach# Function to check if N contains# digit D in itdef findDigit(N, D): # Iterate until N is positive while (N > 0): # Find the last digit a = N % 10 # If the last digit is the # same as digit D if (a == D): return True N /= 10 # Return false return False# Function to check if the value of# N can be represented as sum of# integers having digit d in itdef check(N, D): # Iterate until N is positive while (N > 0): # Check if N contains digit # D or not if (findDigit(N, D) == True): return True # Subtracting D from N N -= D # Return false return False# Driver Codeif __name__ == "__main__": N = 24 D = 7 if (check(N, D)): print("Yes") else: print("No")# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System; class GFG{ // Function to check if N contains// digit D in itstatic bool findDigit(int N, int D){ // Iterate until N is positive while (N > 0) { // Find the last digit int a = N % 10; // If the last digit is the // same as digit D if (a == D) { return true; } N /= 10; } // Return false return false;} // Function to check if the value of// N can be represented as sum of// integers having digit d in itstatic bool check(int N, int D){ // Iterate until N is positive while (N > 0) { // Check if N contains digit // D or not if (findDigit(N, D) == true) { return true; } // Subtracting D from N N -= D; } // Return false return false;} // Driver Codepublic static void Main(){ int N = 24; int D = 7; if (check(N, D)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } }}// This code is contributed by code_hunt. |
Javascript
<script>// javascript program for the above approach// Function to check if N contains// digit D in itfunction findDigit(N, D){ // Iterate until N is positive while (N > 0) { // Find the last digit let a = N % 10; // If the last digit is the // same as digit D if (a == D) { return true; } N = Math.floor(N / 10); } // Return false return false;} // Function to check if the value of// N can be represented as sum of// integers having digit d in itfunction check(N, D){ // Iterate until N is positive while (N > 0) { // Check if N contains digit // D or not if (findDigit(N, D) == true) { return true; } // Subtracting D from N N -= D; } // Return false return false;}// Driver Code let N = 24; let D = 7; if (check(N, D)) { document.write("Yes"); } else { document.write("No"); }</script> |
Временная сложность: O(N)
Космическая сложность: O(1)