给定一系列正整数,请按要求对数字进行分类,并输出以下5个数字:
A1 = 能被5整除的数字中所有偶数的和;
A2 = 将被5除后余1的数字按给出顺序进行交错求和,即计算n1-n2+n3-n4...;
A3 = 被5除后余2的数字的个数;
A4 = 被5除后余3的数字的平均数,精确到小数点后1位;
A5 = 被5除后余4的数字中最大数字。
输入格式:
每个输入包含1个测试用例。每个测试用例先给出一个不超过1000的正整数N,随后给出N个不超过1000的待分类的正整数。数字间以空格分隔。
输出格式:
对给定的N个正整数,按题目要求计算A1~A5并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。
若其中某一类数字不存在,则在相应位置输出“N”。
输入样例1:
13 1 2 3 4 5 6 7 8 9 10 20 16 18
输出样例1:
30 11 2 9.7 9
输入样例2:
8 1 2 4 5 6 7 9 16
输出样例2:
N 11 2 N 9
import java.util.Scanner;
import java.math.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B1012 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
int num[] = new int[1000];
String[] str;
str = rd.readLine().split("\\s");
for (int i = 0; i < N; i++)
{
num[i] = Integer.parseInt(str[i]);
}
int A1 = 0, A2 = 0, A3 = 0, A5 = 0;
double A4 = 0;
int count = 0;
double sum = 0;
double avgcount = 0;
boolean existA1 = false, existA2 = false, existA3 = false, existA4 = false, existA5 = false;
for (int j = 0; j < N; j++)
{
if (num[j] % 10 == 0)
{
A1 += num[j];
existA1 = true;
}
if (num[j] % 5 == 1)
{
count++;
A2 = (int) (A2 + Math.pow(-1, (count+1)) * num[j]);
existA2 = true;
}
if (num[j] % 5 == 2)
{
A3 += 1;
existA3 = true;
}
if (num[j] % 5 == 3)
{
sum += num[j];
avgcount++;
existA4 = true;
}
if (num[j] % 5 == 4)
{
if (num[j] > A5)
{
A5 = num[j];
existA5 = true;
}
}
}
if(existA1)
{
System.out.print(A1+" ");
}
else
{
System.out.print("N ");
}
if(existA2)
{
System.out.print(A2+" ");
}
else
{
System.out.print("N ");
}
if(existA3)
{
System.out.print(A3+" ");
}
else
{
System.out.print("N ");
}
if(existA4)
{
A4 = sum / avgcount;
System.out.printf("%.1f", A4+" ");
}
else
{
System.out.print("N ");
}
if(existA5)
{
System.out.print(A5);
}
else
{
System.out.print("N");
}
in.close();
}
}
测评系统给的时间100ms, 之前用scanner超时,后用bufferedreader还是超时,不太清楚是什么占时间?该怎么优化?感谢!