题目内容
一个多项式可以表达为x的各次幂与系数乘积的和,比如:
2
x
6
+
3
x
5
+
12
x
3
−
6
x
+
20
2x^6+3x^5+12x^3-6x+20
2x6+3x5+12x3−6x+20。
现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出。
程序要处理的幂最大为100。
输入格式
总共要输入两个多项式,每个多项式的输入格式如下:
每行输入两个数字,第一个表示幂次,第二个表示该幂次的系数,所有的系数都是整数。第一行一定是最高幂,最后一行一定是0次幂。
注意第一行和最后一行之间不一定按照幂次降低顺序排列;如果某个幂次的系数为0,就不出现在输入数据中了;0次幂的系数为0时还是会出现在输入数据中。
输出格式
从最高幂开始依次降到0幂,如:
2
x
6
+
3
x
5
+
12
x
3
−
6
x
+
20
2x^6+3x^5+12x^3-6x+20
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
解析:
一定要注意几个点:
1.只有常数项的时候
2.系数为1时候,系数不输出
3.指数为1时候,指数不输出
4.常数项即使为0,也要输出
答案1
import java.util.Scanner;
public class Main {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int z=0,x=0,c=0,key=0,j;
int []s=new int [101];
while(in.hasNext()) {
z=in.nextInt();
x=in.nextInt();
s[z]+=x;
if(z==0) c++;
if(c==2) break; //读到两次指数为0,跳出循环
}
for(j=100;j>0;j--) {
if(s[j]!=0) {
key++;//记录是否是第一项
if(key==1) {//第一项直接输出
if(s[j]!=1)
System.out.print(s[j]);
System.out.print("x");
if(j!=1)
System.out.print(j);
}
else {//不是第一项输出“+”
if(s[j]>0) System.out.print("+");
if(s[j]!=1)
System.out.print(s[j]);
System.out.print("x");
if(j!=1)
System.out.print(j);
}
}
}
if(s[j]>=0&&key>0)System.out.print("+"); //最后一项一定是0次幂
System.out.print(s[j]);
}
}
答案2:(原博客)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int c1,p1,c2,p2,i;
int[] x=new int[101];
do
{
p1=in.nextInt();
c1=in.nextInt();
x[p1]+=c1;
}while(p1!=0);
do
{
p2=in.nextInt();
c2=in.nextInt();
x[p2]+=c2;
}while(p2!=0);
boolean Isfu=true;
boolean Ispr=false;
for(i=x.length-1;i>=0;i--)
{
if(x[i]!=0)
{
Ispr=true;
if(x[i]<0)
{
Isfu=true;
}
if(Isfu==true)
{
Isfu=false;
}
else
{
System.out.print("+");
}
if(x[i]!=1)
{
System.out.print(x[i]);
}
if(i!=1 && i!=0)
{
System.out.print("x"+i);
}
if(i==1)
{
System.out.print("x");
}
}
else
{
if(i==0)
{
if(Ispr==true && x[i]!=0)
{
System.out.print("+");
System.out.print(x[i]);
}
if(Ispr==false)
{
System.out.print(x[i]);
}
}
}
}
}
}