ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อค้นหาจำนวนคำนำหน้าของอาร์เรย์ไบนารีที่หารด้วย 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