小编准备考PAT甲级的证,因此开始刷题中。将刷过的题及自己所编的代码进行整理分享。
题目描述
This time, you are supposed to find A+B where A and B are two polynomials.
输入描述:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N1 aN1 N2 aN2 … NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.
输出描述:
For each test case you should output the sum 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 to 1 decimal place.
输入例子:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
输出例子:
3 2 1.5 1 2.9 0 3.2
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
/**
* A+B for Polynomials
*
* @author Liu
* @version 4.0
*
*/
public class Match1002 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashMap<Integer, Double> mapC = new HashMap<>();
int numA = scanner.nextInt();
for (int i = 1; i <= numA; i++) {
int a = scanner.nextInt();
double b = scanner.nextDouble();
mapC.put(a, b);
}
int numB = scanner.nextInt();
for (int i = 1; i <= numB; i++) {
int a = scanner.nextInt();
double b = scanner.nextDouble();
if (mapC.containsKey(a) && (mapC.get(a) + b == 0)) {
mapC.remove(a);
continue;
} else if (mapC.containsKey(a)) {
double sum = b + mapC.get(a);
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
mapC.put(a, sum);
} else {
mapC.put(a, b);
}
}
Object[] key = mapC.keySet().toArray();
Arrays.sort(key);
System.out.print(key.length);
for (int i = key.length - 1; i >= 0; i--) {
System.out.print(" " + key[i] + " " + mapC.get(key[i]));
}
}
}
解题思路:
本题的解法主要是使用了HashMap,以及Arrays.sort()方法。首先将第一个表达式存储在mapC当中,其中mapC的key值为指数,value值为系数。在B表达式进行输入时,要判断A表达式中是否有与B表达式该项相同的指数。若有,则判断相加后是否为0,若为0,则mapC中去出该项;若不为0,则mapC中要更新该指数对应的系数。此部分需要注意的是,float、double型数据直接进行加法运算,有可能因为精度问题导致计算错误,因此使用
BigDecimal bg = new BigDecimal(sum);
sum = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
mapC.put(a, sum);
进行设置,保留小数点后一位小数(题目要求)。若A表达式中没有与B表达式该项相同的指数,则直接将该项加入到mapC中。
输出最终计算结果,要求指数从大到小,因此使用
Object[] key = mapC.keySet().toArray();
Arrays.sort(key);
让mapC根据key值(指数)进行排序,排序后的结果为指数从小到大。最后输出时从后向前输出即可。