Java-数字分类 (20)

来源:互联网 发布:英雄无敌3 数据修改 编辑:程序博客网 时间:2024/06/03 19:29

题目描述

给定一系列正整数,请按要求对数字进行分类,并输出以下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”。

输入例子:

13 1 2 3 4 5 6 7 8 9 10 20 16 18

输出例子:

30 11 2 9.7 9
import java.util.Scanner;public class sortNum {public static void main(String[] args) {long[] A = new long[5];//用于存储打印输出的内容int[] count = new int[5];//用于存储满足A1...A5分类的计数值Scanner in = new Scanner(System.in);int N = in.nextInt();int status = 0;//用于切换A2中加减情况for(int i = 0; i < N; i++){long num = in.nextLong();switch ((int)(num % 5)) {case 0:if(num%2 == 0){A[0] += num;count[0]++;}break;case 1:if(status%2 == 0){A[1] += num;status = 1;}else {A[1] -= num;status = 0;}count[1]++;break;case 2:A[2]++;count[2]++;break;case 3:count[3]++;A[3] += num;break;case 4:count[4]++;if(num>A[4]){A[4] = num;}default:break;}}//for (int i =0; i < 4; i++) {//if(count[i] != 0){//if(i != 3)//System.out.print(A[i]+" ");//else //System.out.print(Float.valueOf(String.format("%.1f", (A[3]/(float)count[3])))+" ");//}//else {//System.out.print("N ");//}//}//if (count[4] != 0) {//System.out.println(A[4]);//} else {//System.out.print("N");//}StringBuffer sBuffer = new StringBuffer();for (int i =0; i < 5; i++) {if (count[i] != 0) {if (i != 3) {sBuffer.append(A[i]).append(" ");}else {sBuffer.append(Float.valueOf(String.format("%.1f", (A[3]/(float)count[3])))).append(" ");}}else {sBuffer.append("N").append(" ");}}sBuffer.deleteCharAt(sBuffer.length()-1);System.out.println(sBuffer);}}


原创粉丝点击