PAT-basic-1010 一元多项式求导 java
一、题目
设计函数求一元多项式的导数。(注:xn(n为整数)的一阶导数为nxn−1。)
输入格式:
以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过 1000 的整数)。数字间以空格分隔。
输出格式:
以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是 0,但是表示为 0 0
。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:
12 3 -10 1 6 0
二、解析
用一个数组来存储即可,数组下标用来表示指数,值用来表示系数。遇到系数为0的不输出。需要注意0 0
的情况,只需要在最开始判断一下就行了,如果最高指数为0,则说明表达式是常数。
三、代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str[] = input.nextLine().split("\\s+");
if(str.length==0) return;
int maxExp = Integer.parseInt(str[1]);
if(maxExp == 0) {
System.out.println("0 0");
return;
}
int coe[] = new int[maxExp];
for(int i=0; i< str.length; i+=2){
int newCoe = Integer.parseInt(str[i]);
int newExp = Integer.parseInt(str[i+1]);
if(newExp > 0)
coe[newExp-1] += newCoe * newExp;
}
for(int i=coe.length-1; i>=0; i--){
if(coe[i]!=0){
if(i==coe.length-1)
System.out.printf("%d %d", coe[i], i);
else
System.out.printf(" %d %d", coe[i], i);
}
}
}
}