思路:首先判断数组的和是否为偶数,如果不是则直接输出-1;如果是,则对数组中的每个数进行除2操作,直到所有数都变成奇数,记录操作次数。最后输出操作次数。

代码如下:

#include <iostream>
using namespace std;

int main() {
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    int sum = 0;
    int a[n];
    for (int i = 0; i < n; i++) {
      cin >> a[i];
      sum += a[i];
    }
    if (sum % 2 != 0) {
      cout << -1 << endl;
    } else {
      int count = 0;
      for (int i = 0; i < n; i++) {
        while (a[i] % 2 == 0) {
          a[i] /= 2;
          count++;
        }
      }
      cout << count << endl;
    }
  }
  return 0;
}
C++ 数组操作:最少除2次数获得开心数

原文地址: https://www.cveoy.top/t/topic/ord4 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录