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
-
C++でソートされたバイナリ配列の1を数えます
このチュートリアルでは、ソートされたバイナリ配列で1を見つけるプログラムについて説明します。 このために、1と0のみを含む配列が提供されます。私たちのタスクは、配列に存在する1の数を数えることです。 例 #include <bits/stdc++.h> using namespace std; //returning the count of 1 int countOnes(bool arr[], int low, int high){ if (high >= low){ int mid = low + (
-
配列のすべての要素をC++で4で割り切れるようにするための最小手順
問題の説明 サイズnの配列が与えられた場合、タスクは、配列のすべての要素を4で割り切れるのに必要な最小ステップ数を見つけることです。ステップは、配列から任意の2つの要素を削除し、これらの要素の合計を加算することとして定義されます。アレイへ 例 入力配列が{1、2、0、2、4、3}の場合、3つの操作が必要です- 1 + 3 = 4 2 + 2 = 4 0 + 4 = 4 アルゴリズム 1. Sum of all the elements of the array should be divisible by If not, this task is not possible 2. Initi