【PAT】1012 數字分類 (20 分)
阿新 • • 發佈:2019-01-06
1012 數字分類 (20 分)
給定一系列正整數,請按要求對數字進行分類,並輸出以下 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; public class Main { static int [] num = new int[1005]; public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); int i; int a1 = 0,a2 = 0,a3 = 0,a5 = -1; int a4 = 0; int cout4 = 0; int flag = 1; boolean a22 = false; for (i = 0; i < N ;i++){ num[i] = in.nextInt(); if (num[i] % 5 == 0 && num[i] % 2 == 0){ a1 += num[i]; } if (num[i] % 5 == 1){ a2 += (num[i] * flag); flag = flag * (-1); a22 = true; } if (num[i] % 5 == 2){ a3++; } if (num[i] % 5 == 3 ){ cout4 ++; a4 += num[i]; } if (num[i] % 5 == 4){ if (a5 < num[i]){ a5 = num[i]; } } } if (a1 != 0){ System.out.print(a1 + " "); }else { System.out.print("N "); } if (a22){ System.out.print(a2 + " "); }else { System.out.print("N "); } if (a3 != 0){ System.out.print(a3 + " "); }else { System.out.print("N "); } if (cout4 != 0){ System.out.printf("%.1f",(1.0 * a4 / cout4)); System.out.print(" "); }else { System.out.print("N "); } if (a5 != -1){ System.out.print(a5); }else { System.out.print("N"); } } }