
我们给出了一个数字 N 以及一个由 M 位数字组成的数组。我们的工作是找到n个数 由给定的 M 位数字组成的可被 5 整除的数字。
让我们看一些示例来理解问题的输入和输出。
In -
N = 2
M = 3
arr = {5, 6, 3}出局 -
2
有 2 N 个数字 35 和 65 可能被 5 整除。让我们看另一个例子。
输入 -
立即学习“C++免费学习笔记(深入)”;
N = 1
M = 7
arr = {2, 3, 4, 5, 6, 7, 8}输出-
1
给定数组中只有 1 个 1 位数字可以被 5 整除。因此,我们的任务是找到给定的 N 个数字可以被 5 整除的数字的个数。
数字必须以数字 0 或 5 结尾才能被 5 整除。让我们看看算法
以下是上述算法的C++实现
#include <bits/stdc++.h>
using 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
以上就是用C++编写的由M个数字组成的N位数中能被5整除的数字的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号