题目内容:
一个多项式可以表达为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.*;
public class Main {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int[] a;
int i,fir=0;
a=new int[101];
RU:
for(i=0;i<a.length;i++) {
if(in.nextInt()==i) {
if(i==0) {
fir=a[0];
}
a[i]+=in.nextInt();
if(a[0]>fir) {
break RU;
}
}
}
for(i=100;i>=0;i--) {
if(i==1) {
System.out.print(a[i]+"x"+i);
}
if(a[i]!=0) {
if(i==1) {
System.out.print(a[i]+"x"+"+");
}
if(i==0) {
System.out.print(a[i]);
}
else {
System.out.print(a[i]+"x"+i+"+");
}
}
}
}
}
package spring.annotation.day4.threadlocal;
import java.util.*;
/**
* @author : cuantianhou 2020/4/9
*/
public class Solution {
public static void main(String[] args) throws Exception {
String split = " ";
Scanner scanner = new Scanner(System.in);
Map<String,Integer> map = new TreeMap<>(Comparator.reverseOrder());
for(int i = 0; i<2; i++){
String []s = scanner.nextLine().split(split);
int max = Integer.parseInt(s[0]);
if(map.get(s[0])==null) {
map.put(s[0], Integer.parseInt(s[1]));
}else {
map.put(s[0], map.get(s[0])+Integer.parseInt(s[1]));
}
while(Integer.parseInt(s[0]) != 0){
s = scanner.nextLine().split(split);
if(max > Integer.parseInt(s[0]) && map.get(s[0]) == null){
map.put(s[0],Integer.parseInt(s[1]));
}else if(max > Integer.parseInt(s[0]) && map.get(s[0]) != null){
map.put(s[0],map.get(s[0])+Integer.parseInt(s[1]));
}else{
throw new Exception("exception");
}
}
}
StringBuilder expression = new StringBuilder();
for(Map.Entry entry:map.entrySet()){
String key = (String)entry.getKey();
Integer value =(Integer) entry.getValue();
if(0 == value){
continue;
}
if(key.equals("0") && expression.length() == 0 ){
expression.append(value);
}else if(key.equals("0") && expression.length() != 0){
expression.append("+"+value);
}else if(!key.equals("0") && expression.length() == 0 ){
expression.append(value+"x"+key);
}else if(!key.equals("0") && expression.length() != 0){
expression.append("+"+value+"x"+key);
}
}
System.out.println(expression.toString());
}
}
我测试可以