在 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

更新于:17-Feb-2020

90 次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.