首页 > 其他 > 详细

PAT 1012 数字分类

时间:2021-03-17 17:21:31      阅读:34      评论:0      收藏:0      [点我收藏+]

给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:

  • A?1?? = 能被 5 整除的数字中所有偶数的和;
  • A?2?? = 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n?1???n?2??+n?3???n?4???;
  • A?3?? = 被 5 除后余 2 的数字的个数;
  • A?4?? = 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位;
  • A?5?? = 被 5 除后余 4 的数字中最大数字。

愚蠢版本代码,便于理解,有时间再写稍微简单的代码

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class pat1012 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String []str = scanner.nextLine().split(" ");

        List<Integer> lists = new ArrayList();
        int sum =0;
        int A1=0;//A1
        int A2=0;
        int A3=0;
        float A4=0;
        int A5=0;

        for(int i=1;i<str.length;i++){
            if(Integer.parseInt(str[i])%5==0&&Integer.parseInt(str[i])%2==0){
                A1 = A1 + Integer.parseInt(str[i]);

            }
            if(Integer.parseInt(str[i])%5==1){
                lists.add(Integer.parseInt(str[i]));
            }
            if(Integer.parseInt(str[i])%5==2){
                A3++;
            }
            if(Integer.parseInt(str[i])%5==3){
                A4 = A4+Float.parseFloat(str[i]);
                sum++;
            }
            if(Integer.parseInt(str[i])%5==4&&Integer.parseInt(str[i])>=A5){
                A5 = Integer.parseInt(str[i]);
            }

        }

        for(int i=0;i<lists.size();i++){
            A2 = (int)(A2+Math.pow(-1,i)*lists.get(i));
        }
        if(A1==0){
            System.out.print("N ");
        }else
        {
            System.out.print(A1+" ");
        }
        if(lists.size()==0){//可能A2的和就是0,所以不能用A2==0作为判断条件
            System.out.print("N ");
        }else
        {
            System.out.print(A2+" ");
        }
        if(A3==0){
            System.out.print("N ");
        }else
        {
            System.out.print(A3+" ");
        }
        if(A4==0){
            System.out.print("N ");
        }else
        {
            A4 = A4/sum;
            System.out.print(String.format("%.1f",A4)+" ");
        }
        if(A5==0){
            System.out.print("N");
        }else
        {
            System.out.print(A5);
        }

    }
}

 

PAT 1012 数字分类

原文:https://www.cnblogs.com/tonychen88/p/14550302.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!