PAT练习题(甲级) 1009 Product of Polynomials (25分)(Java实现)

PAT练习题 1009 Product of Polynomials (25分)

题干

This time, you are supposed to find A×B where A and B are two polynomials.

Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N1 a​N1 N2 aN2 … NK aNK

where K is the number of nonzero terms in the polynomial, N​iand a​Ni(i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N​K<⋯<N2<N1​ ≤1000.

Output Specification:
For each test case you should output the product of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate up to 1 decimal place.

Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:
3 3 3.6 2 6.0 1 1.6

题意

  • 两个多项式相乘,并进行格式化输出
  • 这道题和1002题的多项式相加很像,保留一位小数输出就行

解题思路

  • 将两个多项式存到数组里,然后相乘,这里很容易就想到双重for循环实现
  • 每一项的指数就可以作为数组中的索引,然后存储对应项的系数
  • 我看网上很多人说用Java写这道题有一个测试点不会通过,我也不知道是哪个

代码实现

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author: 胡奇夫
 * @QQ: 1579328766
 * @CreateTime: 2020-05-11-22-19
 * @Descirption: Pat甲级1009
 */
public class Testnine {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        double[] list1 = new double[1001];//第一行输入
        double[] list2 = new double[1001];//第二行输入
        double[] list3 = new double[2002];//运算后的数组
        int sum = 0;//运算后的多项式的非零项个数
        String[] strlist = br.readLine().split(" ");
        for(int i = 1;i<strlist.length-1;i+=2)
        {
            list1[Integer.parseInt(strlist[i])] = Double.parseDouble(strlist[i+1]);
        }
        strlist = br.readLine().split(" ");
        for(int i = 1;i<strlist.length-1;i+=2)
        {
            list2[Integer.parseInt(strlist[i])] = Double.parseDouble(strlist[i+1]);
        }

        //进行多项式相乘,并将结果存储到list3里
        for(int i = 0;i<list1.length;i++)
        {
            if(list1[i]!=0.0)
            {
                for(int j = 0;j<list2.length;j++)
                {
                    if(list2[j]!=0.0)
                    {
                        list3[i+j] += list1[i]*list2[j];
                    }
                }
            }
        }

        //计算运算后的多项式中非零项的个数
        for(int i = 0;i<list3.length;i++)
        {
            if(list3[i]!=0.0) sum++;
        }
        System.out.print(sum);

        //格式化输出
        for(int i = list3.length-1;i>=0;i--)
        {
            if(list3[i]!=0.0)
            {
                System.out.print(" "+i+" ");
                System.out.printf("%.1f",list3[i]);
            }
        }
        System.out.println();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45062103/article/details/106090608
今日推荐