题
设计函数分别求两个一元多项式的乘积与和。
输入格式
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0。
输入样例
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
做题出现答案错误,实在是找不到原因,在线求大神指出,太为难我了!!!!!!!!!!!
以下是代码,跪求帮助
代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
String contents1 = input.nextLine();
String[] number = contents1.split("\\s+");
Main pl = new Main();
String contents2 = input2.nextLine();
String number2[] = contents2.split("\\s+");
List<Ploy> list1 = pl.readPoly(number,Integer.parseInt(number[0]));
List<Ploy> list2 = pl.readPoly(number2,Integer.parseInt(number2[0]));
List<Ploy> list = pl.addPloy(list1, list2);
List<Ploy> list3 = pl.multiplyPloy(list1, list2);
pl.printPloy(list3);
pl.printPloy(list);
}
List<Ploy> readPoly(String number[],int num){
List<Ploy> list = new ArrayList<>();
for (int i=0;i<num;i++){
int j=2*i+1;
Ploy ploy = new Ploy();
ploy.setCoe( Integer.parseInt(number[j]));
ploy.setExpo( Integer.parseInt(number[j+1]));
list.add(ploy);
}
return list;
}
void printPloy(List<Ploy> list){
StringBuffer sb = new StringBuffer();
if (list.size()>0){
for (Ploy ploy : list){
sb.append(ploy.getCoe()+" "+ploy.getExpo()+" ");
}
String sb2 = sb.substring(0, sb.length() - 1);
System.out.println(sb2);
}else
System.out.println(0+" "+0);
}
class Ploy{
int coe;//系数
int expo;//指数
public int getExpo() {
return expo;
}
public void setExpo(int expo) {
this.expo = expo;
}
public int getCoe() {
return coe;
}
public void setCoe(int coe) {
this.coe = coe;
}
public Ploy(int coe, int expo) {
this.coe = coe;
this.expo = expo;
}
public Ploy() {
}
}
List<Ploy> addPloy(List<Ploy> list1 , List<Ploy> list2){
int i=0,j=0;
List<Ploy> list = new ArrayList<>();
while(i<list1.size() && j<list2.size()){
if (list1.get(i).getExpo() > list2.get(j).getExpo()){
list.add(list1.get(i));
i++;
}
else if (list1.get(i).getExpo() < list2.get(j).getExpo()){
list.add(list2.get(j));
j++;
}
else{
if (list2.get(j).getCoe()+list1.get(i).getCoe()!=0){
Ploy ploy = new Ploy(list2.get(j).getCoe()+list1.get(i).getCoe(),list1.get(i).getExpo());
list.add(ploy);
}
j++;
i++;
}
}
if (i<list1.size()){
for (int a=i;a<list1.size();a++){
list.add(list1.get(a));
}
}
if (j<list2.size()){
for (int a=j;a<list2.size();a++){
list.add(list2.get(a));
}
}
return list;
}
List<Ploy> multiplyPloy(List<Ploy> list1 , List<Ploy> list2){
List<Ploy> list = new ArrayList<>();
for(Ploy ploy1 : list1){
int coe1 = ploy1.getCoe();
int expo1 = ploy1.getExpo();
List<Ploy> tmpList = new ArrayList<>();
for(Ploy ploy2 : list2){
Ploy ploy = new Ploy();
ploy.setCoe(ploy2.getCoe()*coe1);
ploy.setExpo(ploy2.getExpo()+expo1);
tmpList.add(ploy);
}
list=addPloy(list,tmpList);
}
return list;
}
}