由C++中的M位组成的可被5整除的N位数字
在本教程中,我们将编写一个程序来查找可以使用数组中给定的m位数字组成的总数。让我们看一个例子。
输入
n = 2 m = 3 arr = {5, 6, 3}输出结果
让我们看看解决问题的步骤。
检查0和5,因为数字必须包含0或5才能被5整除。
如果同时存在0和5,则有两种方法可以在单位位中放置数字。否则将只有一种放置数字的方法。
现在,剩下的地方可以有m-1,m-2,m-3,...n种方法来分别填充它们。
让我们看看代码。
#includeusing namespace std; int numbers(int n, int m, int arr[]) { bool isZeroPresent = false, isFivePresent = false; int numbersCount = 0; if (m < n) { return -1; } for (int i = 0; i < m; i++) { if (arr[i] == 0) { isZeroPresent = true; } if (arr[i] == 5) { isFivePresent = true; } } if (isZeroPresent && isFivePresent) { numbersCount = 2; for (int i = 0; i < n - 1; i++) { m--; numbersCount = numbersCount * m; } } else if (isZeroPresent || isFivePresent) { numbersCount = 1; for (int i = 0; i < n - 1; i++) { m--; numbersCount = numbersCount * m; } } else { return -1; } return numbersCount; } int main() { int arr[] = {5, 6, 3}; cout << numbers(2, 3, arr) << endl; return 0; }
如果你运行上面的代码,那么你会得到下面的结果。
2
结论
如果您对本教程有任何疑问,请在评论部分提及。