课程:零基础学Java语言(翁恺)
多项式加法
题目内容:
一个多项式可以表达为x的各次幂与系数乘积的和,比如:2x6+3x5+12x3+6x+20
现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出。程序要处理的幂最大为100。
输入格式:
总共要输入两个多项式,每个多项式的输入格式如下:
每行输入两个数字,第一个表示幂次,第二个表示该幂次的系数,所有的系数都是整数。第一行一定是最高幂,最后一行一定是0次幂。
注意第一行和最后一行之间不一定按照幂次降低顺序排列;如果某个幂次的系数为0,就不出现在输入数据中了;0次幂的系数为0时还是会出现在输入数据中。
输出格式:
从最高幂开始依次降到0幂,如:
2x6+3x5+12x3-6x+20
注意其中的x是小写字母x,而且所有的符号之间都没有空格,如果某个幂的系数为0则不需要有那项。
输入样例:
6 2
5 3
3 12
1 6
0 20
6 2
5 3
2 12
1 6
0 20
输出样例:
4x6+6x5+12x3+12x2+12x+40
时间限制:500ms内存限制:32000kb
注意点:
- 系数为1或-1时,1不输出,如 x 和 -x
- 指数为1时,1不输出,如 x
- 系数为0时,对应单项式不输出
- 仅有常数项时,只输出常数项数值,包括0
代码一:
import java.util.Scanner;
public class exercise{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int p = in.nextInt();//第一个多项式的最高幂
int c = in.nextInt();//第一个多项式最高幂的系数
int count = 0;
int maxP = p;
//保存第一个多项式的系数
int[] coefficients1 = new int[maxP+1];
while( p!=0 ) {
coefficients1[p] = c;
p = in.nextInt();
c = in.nextInt();
}
if( p==0 ) {
count++;
if(count==1) {
coefficients1[p] = c;
p = in.nextInt();//第二个多项式的最高幂
c = in.nextInt();//第二个多项式最高幂的系数
}
}
//保存第二个多项式的系数
if(p > maxP) {
maxP = p;
}
int[] coefficients2 = new int[maxP+1];
while( p!=0 ) {
coefficients2[p] = c;
p = in.nextInt();
c = in.nextInt();
}
if( p==0 ) {
count++;
if(count==2) {
coefficients2[p] = c;
}
}
//相同次幂系数相加
int[] sumOfCoefts = new int[maxP+1];
for(int i=0;i<sumOfCoefts.length;i++) {
sumOfCoefts[i] = coefficients1[i] + coefficients2[i];
}
//输出多项式
int num = 0;//已输出的单项式的个数
int j=sumOfCoefts.length-1;
for(;j>0;j--) {
int ce = sumOfCoefts[j];
if(ce!=0) {
num++;
if(num==1) {
if(ce>1 || ce<-1) {
System.out.print(ce);
}
else if(ce==-1) {
System.out.print("-");
}
System.out.print("x");
if(j!=1) {
System.out.print(j);
}
}
else {
if(ce>0) {
System.out.print("+");
if(ce>1) {
System.out.print(ce);
}
System.out.print("x");
}
else {
if(ce<-1) {
System.out.print(ce);
}
else {
System.out.print("-");
}
System.out.print("x");
}
if(j!=1) {
System.out.print(j);
}
}
}
}
//常数项
int c0 = sumOfCoefts[0];
if(num!=0 && c0>0) {
System.out.print("+");
}
System.out.print(c0);
}
}
代码二:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int p,c;
int count = 0;
int[] sumOfCoefts = new int[101];
while(count<2) {
p = in.nextInt();
c = in.nextInt();
sumOfCoefts[p] += c;
if(p==0) {
count++;
}
}
//输出多项式
int num = 0;//已输出的单项式的个数
int j=sumOfCoefts.length-1;
for(;j>0;j--) {
int ce = sumOfCoefts[j];
if(ce!=0) {
num++;
if(num==1) {
if(ce>1 || ce<-1) {
System.out.print(ce);
}
else if(ce==-1) {
System.out.print("-");
}
System.out.print("x");
if(j!=1) {
System.out.print(j);
}
}
else {
if(ce>0) {
System.out.print("+");
if(ce>1) {
System.out.print(ce);
}
System.out.print("x");
}
else {
if(ce<-1) {
System.out.print(ce);
}
else {
System.out.print("-");
}
System.out.print("x");
}
if(j!=1) {
System.out.print(j);
}
}
}
}
//常数项
int c0 = sumOfCoefts[0];
if(num!=0 && c0>0) {
System.out.print("+");
}
System.out.print(c0);
}
}