给定一个数组和一个整数N,使用C++中的STL查找可被N整除的元素
例子:
Input: a[] = {1, 2, 3, 4, 5, 10}, N = 2
Output: 3
Explanation:
As 2, 4, and 10 are divisible by 2
Therefore the output is 3
Input:a[] = {4, 3, 5, 9, 11}, N = 5
Output: 1
Explanation:
As only 5 is divisible by 5
Therefore the output is 3
方法:可以使用C++中的count_if()方法来实现
句法:
count_if(lower_bound, upper_bound, function)
其中函数将一个给定序列的元素一对一地作为参数,并根据该函数指定的条件返回一个布尔值。
在这种情况下,该函数将是:
bool isDiv(int i)
{
if (i % N == 0)
return true;
else
return false;
}
下面是上述方法的实现:
// C++ simple program to
// find elements which are
// divisible by N
#include
using namespace std;
int N;
// Function to check
// if the element is divisible by N
bool isDiv(int i)
{
if (i % N == 0)
return true;
else
return false;
}
// Driver code
int main()
{
int a[] = { 1, 2, 6, 3, 4, 5 };
N = 2;
int n = sizeof(a) / sizeof(a[0]);
int count = count_if(a, a + n, isDiv);
cout << "Elements divisible by "
<< N << ": " << count;
return 0;
}
输出:
Elements divisible by 2: 3
想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。