이 튜토리얼에서는 정렬된 이진 배열에서 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 + (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