1

给定一个包含 N 个数字的数组 A,输出数组中总和可被 4 整除的对数。

输入的第一行包含一个整数 T,表示测试用例的数量。

T 测试用例的描述如下。

每个测试用例的第一行包含一个整数 N。

第二行包含 N 个空格分隔的整数

A[0] A[1] ... A[N−1]

表示数组编号。

/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
    
/* Name of the class has to be "Main" only if the class is public. */
public class Main {
    public static void main (String[] args) throws java.lang.Exception {
        //Scanner scan = new Scanner(System.in);
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        //int t= scan.nextInt();
        while (t-- > 0) {
            int n = Integer.parseInt(br.readLine());
            long ans=0;
            int[] arr= new int[n];
            String line = br.readLine();
            String[] strs = line.trim().split("\\s+");
            for (int i = 0; i < n; i++) {
                arr[i]=Integer.parseInt(strs[i]);
            }
            int[] count = new int[4];
            for (int i = 0; i < n; i++) {
                count[arr[i] % 4]++;
            }
            for (int i = 1; i <= 1; i++) {
                ans += count[i] * count[4-i];
            }
            ans += (count[2] * (count[2]-1)) / 2;
            //System.out.println(ans);
            ans += (count[0] * (count[0]-1)) / 2;
            System.out.println(ans);                    
        }
    }
}
4

1 回答 1

2

当你读取数组时你做了正确的事情,但是当你读取和值trim时你没有这样做。tn

在这些行中添加trim()调用:

int t = Integer.parseInt(br.readLine().trim());
int n = Integer.parseInt(br.readLine().trim());

在java中将带空格的字符串转换为整数

另外,如果保证数字之间正好用一个空格分隔,最好将字符串拆分替换为

String[] strs = line.trim().split(" ");

因为按一个字符拆分比按正则表达式拆分要快得多 Java 拆分字符串性能

于 2021-08-21T07:50:46.700 回答