PAT 甲级 1002 多项式相加(测试点2 一直不能通过)

这是一个关于解决PAT甲级考试题1002的Java程序,实现两个多项式的相加。程序首先读取输入的多项式系数和指数,然后使用HashMap存储,并进行相加操作。在相加过程中,检查每个系数是否为0以避免冗余项。最后,按升序排列并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.promise.pat;

import java.util.*;

public class P1002_2 {
    public static void main(String[]args){
//        使用Map
//        Key : 指数
//        value: 系数
        Scanner input = new Scanner(System.in);
        String line1 = input.nextLine();
        String line2 = input.nextLine();

        int n1 = Integer.parseInt(line1.split(" ")[0]);
        int n2 = Integer.parseInt(line2.split(" ")[0]);

        HashMap<Integer,Double> ploy1 = getData(line1,n1);
        HashMap<Integer,Double> ploy2 = getData(line2,n2);



        for (Map.Entry<Integer, Double> entry : ploy2.entrySet()) {
           Integer e =  entry.getKey();
           Double c = entry.getValue();

//           ploy1中有 ploy2的key
           if(ploy1.containsKey(e)){
               Double res = c.doubleValue() + ploy1.get(e).doubleValue();
               if(res.doubleValue() == 0){
                   ploy1.remove(e);
               }
               else{
                   ploy1.put(e,res);
               }

           }
//           ploy1中 没有 ploy2的key

           else {
               ploy1.put(e,c);
           }

        }

        int size = ploy1.size();
        if(size == 0){
            System.out.print(size);
        }
        else{
            System.out.print(size+" ");

        }

        //将keySet放入list
        ArrayList<Integer> list= new ArrayList<>(ploy1.keySet());
        //调用sort方法并重写比较器进行升/降序
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1<o2?1:-1;
            }
        });

        Iterator<Integer> iterator = list.iterator();
        //迭代排序后的key的list
        int count = 0;
        while ((iterator.hasNext())){
            Integer key = iterator.next();
            Double value = ploy1.get(key);
            System.out.print(key.intValue()+" "+ value.doubleValue());
            count++;
            if(count != size){
                System.out.print(" ");
            }

        }




    }



    public static HashMap<Integer,Double> getData(String line, int len){
        HashMap<Integer,Double> map = new HashMap<>();

        String[] line1Date = line.split(" ");


        for(int i=1;i<line1Date.length-1;i+=2){
            Integer e = new Integer(line1Date[i]);
            Double c = new Double(line1Date[i+1]);
            if(c == 0){
                continue;
            }

            map.put(e,c);

        }


        return map;
    }

}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值