简单的OJ,但是测试用例却覆盖了如此多的细节,当看到自己的代码没有通过的时候,真的很疑惑,自身能力的局限性却让我怀疑OJ出错,要周全的考虑一件事真不是一件容易的事,慢慢来,还有很长的路。。。最后终于是做出来了:)
多项式加法
题目内容:
一个多项式可以表达为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
输出的可能性(推测):
不能有,如,+-3x5,这是没有考虑系数的正负,都直接输出“+”符号所致,应该要判断正负,正数输出“+”,负数是自带符号的,无需输出符号
两个多项式都为0,相加也为0多项式,所以应输出0
当幂次为0时,即为常数,无需输出x0,如,3x0,-3x0,直接输出3或-3
当幂次为1时,无需输出x1的1,即输出x,如,3x1,-3x1,直接输出3x或-3x
对于系数为1和-1的当幂次不为0时,是不需要输出1或-1的,如,1x3,-1x3,直接输出x3,-x3
其他正常输出就可以了
如何输出第一项时不输出“+”,使用标志变量
code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
final int SIZE=101;
int[] e1=new int[SIZE];
int[] e2=new int[SIZE];
int n1=0,n2=0;
do{
n1=in.nextInt();
n2=in.nextInt();
if( n1>=0 && n1<SIZE )
{
e1[n1]=n2;
}
}while( n1!=0 );
do{
n1=in.nextInt();
n2=in.nextInt();
if( n1>=0 && n1<SIZE )
{
e2[n1]=n2;
}
}while( n1!=0 );
for( int i=0 ; i<SIZE ; i++ ){
if( e2[i]!=0 )
{
e1[i]+=e2[i];
}
}
int flag=0;
int cnt=0;
for( int i=e1.length-1 ; i>=0 ; i-- ){
if( e1[i]!=0 )
{
if( flag==0 )
{
if( i==0 )
{
System.out.print(e1[i]);
cnt++;
}
else if( i==1 )
{
if( e1[i]==1 )
{
System.out.print("x");
}
else if( e1[i]==-1 )
{
System.out.print("-x");
}
else
{
System.out.print(e1[i]+"x");
}
cnt++;
}
else
{
if( e1[i]==1 )
{
System.out.print("x"+i);
}
else if( e1[i]==-1 )
{
System.out.print("-x"+i);
}
else
{
System.out.print(e1[i]+"x"+i);
}
cnt++;
}
flag=1;
}
else
{
if( i==0 )
{
if( e1[i]>0 )
{
System.out.print("+"+e1[i]);
}
else
{
System.out.print(e1[i]);
}
cnt++;
}
else if( i==1 )
{
if( e1[i]>0 )
{
if( e1[i]==1 )
{
System.out.print("+x");
}
else
{
System.out.print("+"+e1[i]+"x");
}
}
else
{
if( e1[i]==-1 )
{
System.out.print("-x");
}
else
{
System.out.print(e1[i]+"x");
}
}
cnt++;
}
else
{
if( e1[i]>0 )
{
if( e1[i]==1 )
{
System.out.print("+x"+i);
}
else
{
System.out.print("+"+e1[i]+"x"+i);
}
}
else
{
if( e1[i]==-1 )
{
System.out.print("-x"+i);
}
else
{
System.out.print(e1[i]+"x"+i);
}
}
cnt++;
}
}
}
}
if( cnt==0 )
{
System.out.print("0");
}
System.out.println();
}
}