多项式加法(5分)
题目内容:
一个多项式可以表达为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
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[] a = new int[101];
int[] b = new int[101];
int i;
boolean max = true;
boolean zero = true;
do
{
i = in.nextInt();
a[i] =in.nextInt();
}while(i>0);
do
{
i = in.nextInt();
b[i] = in.nextInt();
}while(i>0);
for(int j = 100; j >= 0;j--)
{
a[j] = a[j]+b[j];
if(a[j] != 0)
{
zero = false;
}
}
for(int j = 100; j >1;j--)
{
if(a[j] != 0)
{
if(max)
{
if(a[j] == 1)
{
System.out.print("x"+j);
}
else if(a[j] == -1)
{
System.out.print("-x"+j);
}
else
{
System.out.print(a[j]+"x"+j);
}
max = false;
}
else
{
if(a[j] == 1)
{
System.out.print("+x"+j);
}
else if(a[j] == -1)
{
System.out.print("-x"+j);
}
else if (a[j] < 0)
{
System.out.print(a[j]+"x"+j);
}
else if (a[j] > 0)
{
System.out.print("+"+a[j]+"x"+j);
}
}
}
}
if(a[1] == 1)
{
System.out.print("+x");
}
else if(a[1] == -1)
{
System.out.print("-x");
}
else if (a[1] < 0)
{
System.out.print(a[1]+"x");
}
else if (a[1] > 0)
{
System.out.print("+"+a[1]+"x");
}
if (a[1] < 0)
{
System.out.print(a[0]);
}
else if (a[1] > 0)
{
System.out.print("+"+a[0]);
}
if (zero)
System.out.print(0);
}
}
要考虑多项式全为0,显示0,最高幂次前面不显示加号,幂次为1,不显示1,系数为1或-1,不显示1。