在 C++ 中计算给定二进制数组中所有可被 x 整除的前缀的个数
在此教程中,我们将讨论一个程序,用于查找二进制数组中可被 x 整除的前缀个数。
为此,我们将提供二进制数组和一个值 x。我们的任务是查找其前缀可被给定值 x 整除的元素个数。
示例
#include <bits/stdc++.h>
using namespace std;
//counting the elements with prefixes
//divisible by x
int count_divx(int arr[], int n, int x){
int number = 0;
int count = 0;
for (int i = 0; i < n; i++) {
number = number * 2 + arr[i];
//increasing count
if ((number % x == 0))
count += 1;
}
return count;
}
int main(){
int arr[] = { 1, 0, 1, 0, 1, 1, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 2;
cout << count_divx(arr, n, x);
return 0;
}输出
3
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP