在本教程中,我们将讨论在排序的二进制数组中查找1的程序。
为此,我们将提供一个仅包含1和0的数组。我们的任务是计算数组中存在的1的数量。
#include <bits/stdc++.h>
using namespace std;
//返回1的计数
int countOnes(bool arr[], int low, int high){
if (high >= low){
int mid = low + (high - low)/2;
if ( (mid == high || arr[mid+1] == 0) && (arr[mid] == 1))
return mid+1;
if (arr[mid] == 1)
return countOnes(arr, (mid + 1), high);
return countOnes(arr, low, (mid -1));
}
return 0;
}
int main(){
bool arr[] = {1, 1, 1, 1, 0, 0, 0};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Count of 1's in given array is " << countOnes(arr, 0, n-1);
return 0;
}输出结果
Count of 1's in given array is 4