题目

原题链接

设计函数求一元多项式的导数。(注:\\(x^n\\)(n为整数)的一阶导数为 \\(n\*x^{n-1}\\) 。)

**输入格式:**以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

**输出格式:**以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是0,但是表示为“0 0”。

输入样例:
3 4 -5 2 6 1 -2 0

输出样例:
12 3 -10 1 6 0

解析

这道题要确保一定有输出,所以如果输入是0 0则输出也应该是0 0
另外,这道题输入中空格可能不止一个,因此Python里不能用split()来分割数组,而应该换用正则表达式(注意别忘了匹配负数)。

代码

C++解法

#include <iostream>
using namespace std;

int main() {
    cin.tie(0);
    cin.sync_with_stdio(false);

    int a, n;
    bool isFirst = true;
    while (cin >> a >> n) {
        if (n != 0) {
            if (isFirst) {
                isFirst = false;
            } else {
                cout << " ";
            }
            cout << a * n << " " << n - 1;
        }
    }
    if (isFirst)
        cout << "0 0";
    cout << endl;
    return 0;
}

Python解法

import re
read = ""
try:
    while 1:
        read += " " + input()
except:
    pass
read = [int(i) for i in re.findall(r"[\-0-9]+", read)]

ans = []
for i in range(1, len(read), 2):
    a = read[i - 1]
    n = read[i]
    # print(a, n)
    if n != 0:
        ans += [a * n, n - 1]
if len(ans) == 0:
    ans = [0, 0]
print(" ".join([str(i) for i in ans]))

Java解法

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean isFirst = true;
        while (in.hasNextInt()) {
            int a = in.nextInt();
            int n = in.nextInt();

            if (n != 0) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    System.out.print(" ");
                }
                System.out.printf("%d %d", a * n, n - 1);
            }
        }
        if (isFirst){
            System.out.print("0 0");
        }
        System.out.print("\n");

        in.close();
    }
}