PAT Class B Java Implementation _1012. Digital Classification _ with detailed problem-solving notes _09

1012. Number Classification(20)

time limit
100 ms
memory limit
65536 kB
code length limit
8000 B
Judgment procedure
Standard
author
CHEN, Yue

Given a series of positive integers, sort the numbers as required and output the following 5 numbers:

A1 = sum of all even numbers in numbers divisible by 5; A2 = interleaved summation of numbers with remainder 1 after division by 5 in the given order, i.e. calculate n1-n2+n3-n4...; A3 = be The number of digits with a remainder of 2 after division by 5; A4 = the average number of digits with a remainder of 3 after division by 5, accurate to 1 decimal place; A5 = the largest number of digits with a remainder of 4 after division by 5.

Input format:

Each input contains 1 test case. Each test case first gives a positive integer N not exceeding 1000, and then gives N positive integers not exceeding 1000 to be classified. The numbers are separated by spaces.

Output format:

For the given N positive integers, calculate A1~A5 according to the requirements of the question and output them sequentially in one line. Numbers are separated by spaces, but there must be no extra spaces at the end of the line.

If one of the types of numbers does not exist, output "N" in the corresponding position.

Input sample 1:
13 1 2 3 4 5 6 7 8 9 10 20 16 18
Sample output 1:
30 11 2 9.7 9
Input sample 2:
8 1 2 4 5 6 7 9 16
Sample output 2:
N 11 2 N 9

import java.util.Scanner;
public class PAT_B_1012
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		
		int A1 = 0;//Define 5 variables representing numeric categories
		int A2 = 0;
		int A2flag = 1;//Used to assist the interleaved summation, use 1*-1 to change the sign
		int A3 = 0;
		int A4sum = 0;
		int A4cnt = 0;
		int A5 = 0;
		
		for(int i = 0; i < n; i++)
		{
			int num = in.nextInt();//Receive numbers
			if((num % 5 == 0) && (num % 2 == 0))//5 ifs to judge the number category
				A1 = A1 + num;
			if(num % 5 == 1)
			{
				A2 = A2 + (A2flag*num);
				A2flag = A2flag * -1;
			}
			if(num % 5 == 2)
				A3 ++;
			if(num % 5 == 3)
			{
				A4sum = A4sum + num;
				A4cnt++;
			}
			if((num % 5 == 4) && (num > A5))
				A5 = num;
		}
		
		print(A1,1);//Call the output function
		print(A2,0);
		print(A3,0);
		if(A4cnt == 0)
			System.out.print(" N" );
		else
			System.out.printf(" %.1f",(A4sum * 1.0 / A4cnt));
		print(A5,0);
	}
	
	public static void print(int n, int flag )//Output function
	{
		if(flag != 1)
			System.out.print(" ");
		if(n == 0)
			System.out.print("N");
		else
			System.out.print(n);
	}
	

}

drunk. . The submission of Niuke.com passed perfectly, and the submission of PAT completely timed out.

I remembered that Chen Yue's grandmother said not to use Scanner. Sure enough, Scanner is too slow.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326431632&siteId=291194637