题目链接
个人思想
题目要求所有数之积和所有数之和都不为 0 ,那么我们就在输入的数组的时候,记录下数组之和与数组中 0 的个数(这关系到数组之积是否为 0 )。
如果数组中存在 0, 那么首先需要将所有 0 变成 1 。之和,再去判断当前的和是否为 0,如果为0的话,只需要随意将一个正数 + 1即可(为什么是正数呢?如果一个数组和为0,而且不存在 0 的时候,那么必然有一个正数存在;而我们去修改一个负数,可能将该负数变为 0,违背题意)
参考代码
Java
为了避免因为Java自带Scanner读写比较慢的情况影响过题,以后都会使用自己封装的Scanner类
import java.io.*;
public class Main {
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
int t = sc.nextInt();
int n, a;
while (t-- > 0) {
n = sc.nextInt();
int sum = 0, cnt = 0;
for (int i = 1; i <= n; ++i) {
a = sc.nextInt();
sum += a;
if(a == 0) {
cnt++;
}
}
sum += cnt;
if (sum == 0) ++cnt;
out.println(cnt);
}
out.flush();
}
}
class Scanner {
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
// 字符串快速读入对象
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public Scanner() {
}
public int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
}
C/C++
#include<bits/stdc++.h>
using namespace std;
int n, a;
void solve()
{
cin >> n;
int sum = 0, cnt = 0;
for (int i = 1; i <= n; ++i)
{
cin >> a;
sum += a;
if(a == 0) ++cnt;
}
sum += cnt;
if(sum == 0) ++cnt;
cout << cnt << '\n';
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t;
cin >> t;
while(t--)
solve();
}