假设有一个包含一些数字的数组。我们必须告诉最小数将添加多少个数字,以使元素的总和均匀。该数字必须大于0。因此,如果元素的总和为奇数,我们将加1,但是如果总和已经是偶数,则我们将其加2使其成为偶数。
begin s := 0 for each element e from arr, do s := e + s done if s is even, then return 2, otherwise 1 end
#include<iostream>
using namespace std;
int addMinNumber(int arr[], int n) {
int sum = 0;
for(int i = 0; i<n; i++) {
sum += arr[i];
}
return (sum % 2)? 1 : 2;
}
main() {
int arr[] = {5, 8, 4, 7, 5};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Minimum " << addMinNumber(arr, n) << " should be added";
}输出结果
Minimum 1 should be added