3x^2 + 3x + 2^2 - 2x + 6xy + 5*6 + y^6 - 6yx java代码实现合并多项式
时间: 2023-06-04 17:04:31 浏览: 51
下面是Java代码实现合并多项式的例子:
```
import java.util.*;
public class PolynomialMerge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> aCoeffs = new ArrayList<>();
List<Integer> aPowers = new ArrayList<>();
List<Integer> bCoeffs = new ArrayList<>();
List<Integer> bPowers = new ArrayList<>();
System.out.print("Enter the number of terms in the first polynomial: ");
int n1 = sc.nextInt();
System.out.println("Enter the coefficients and powers of the first polynomial:");
for(int i = 0; i < n1; i++) {
int coeff = sc.nextInt();
int pow = sc.nextInt();
aCoeffs.add(coeff);
aPowers.add(pow);
}
System.out.print("Enter the number of terms in the second polynomial: ");
int n2 = sc.nextInt();
System.out.println("Enter the coefficients and powers of the second polynomial:");
for(int i = 0; i < n2; i++) {
int coeff = sc.nextInt();
int pow = sc.nextInt();
bCoeffs.add(coeff);
bPowers.add(pow);
}
List<Integer> cCoeffs = new ArrayList<>();
List<Integer> cPowers = new ArrayList<>();
int aIndex = 0, bIndex = 0;
while(aIndex < n1 && bIndex < n2) {
if(aPowers.get(aIndex) == bPowers.get(bIndex)) {
int sum = aCoeffs.get(aIndex) + bCoeffs.get(bIndex);
if(sum != 0) {
cCoeffs.add(sum);
cPowers.add(aPowers.get(aIndex));
}
aIndex++;
bIndex++;
} else if(aPowers.get(aIndex) > bPowers.get(bIndex)) {
cCoeffs.add(aCoeffs.get(aIndex));
cPowers.add(aPowers.get(aIndex));
aIndex++;
} else {
cCoeffs.add(bCoeffs.get(bIndex));
cPowers.add(bPowers.get(bIndex));
bIndex++;
}
}
while(aIndex < n1) {
cCoeffs.add(aCoeffs.get(aIndex));
cPowers.add(aPowers.get(aIndex));
aIndex++;
}
while(bIndex < n2) {
cCoeffs.add(bCoeffs.get(bIndex));
cPowers.add(bPowers.get(bIndex));
bIndex++;
}
System.out.println("\nResultant polynomial after merging:");
for(int i = 0; i < cCoeffs.size(); i++) {
int coeff = cCoeffs.get(i);
int pow = cPowers.get(i);
System.out.print(coeff + "x^" + pow + " ");
if(i < cCoeffs.size() - 1 && cCoeffs.get(i + 1) >= 0) {
System.out.print("+ ");
}
}
}
}
```
代码中使用了 List 来存储多项式中的系数和次数,并且应用了归并排序的思想来合并两个多项式。