PAT 1012 数字分类 (20分)(Java)

题目描述

给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:
在这里插入图片描述

输入格式:

  每个输入包含 1 个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数。数字间以空格分隔。

输出格式:

  对给定的 N 个正整数,按题目要求计算 A​1​​ ~A​5并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。
  若其中某一类数字不存在,则在相应位置输出 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

代码

package com.hbut.pat;
import java.util.Scanner; 

public class Pat_1012 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		int[] arr = new int[num];
		for(int i = 0 ; i < arr.length ; i ++) {
			arr[i] = sc.nextInt();
		}	
		float[] numArr = new float[5];
		int index = 0;
		int temp = 0 ;
		int pow = 0;
		int a1 = 0;
		int a2 = 0;
		int a3 = 0;
		int a4 = 0;
		int a5 = 0;
		for(int i = 0 ; i < arr.length ; i ++) {
			temp = arr[i];
			if(temp % 5 == 0) {
				if(temp % 2 == 0) {
					numArr[0] = numArr[0] + temp;
				}
			}
			if(temp % 5 == 1) {
				numArr[1] = numArr[1] + ((int)Math.pow(-1, pow)*temp);
				pow ++;
			}
			if(temp % 5 == 2) {
				numArr[2] ++;
			}
			if(temp % 5 == 3) {
				index ++;
				numArr[3] = (numArr[3] + temp);
			}
			if(temp % 5 == 4) {
				if(temp>a5) {
					numArr[4] = temp;
				}
			}
		}
		for(int i = 0 ; i < numArr.length ; i ++) {
			if(i == 4) {
				System.out.print((int)numArr[i]);
			}else if(i == 3) {
				if(numArr[3] == 0) {
					System.out.print("N ");
				}else {
					System.out.print(String.format("%.1f",(numArr[3] / index)) + " ");
				}
			}else if(numArr[i] == 0) {
				System.out.print("N ");
			}else {
				System.out.print((int)numArr[i] + " ");
			}
		}	
	}
}

发布了108 篇原创文章 · 获赞 134 · 访问量 178万+

猜你喜欢

转载自blog.csdn.net/huanglei305/article/details/105118305