题目描述
输入格式
输入共有 2 行
第一行 11个整数,n,表示一元多项式的次数。
第二行有 n+1 个整数,其中第 ii 个整数表示第 n-i+1次项的系数,每两个整数之间用空格隔开。
输出格式
输出共 1 行,按题目所述格式输出多项式。
输入输出样例
代码实现思路:
需要考虑一下这些情况:
(1)如果系数为0,这一项就不输出了;
(2)如果系数为+1/1/-1,且不为常数项,则省略系数,如1x^3直接写成x^3。但是若+1/1/-1是常数项,不能省略。
(3)考虑正数时,需要知道正数可能带符号,如系数输入为+5或5;
(4)如果多项式最高次项为正数,不以"+"开头。
(5)考虑系数全0的情况,输出为0.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string s[110];//不能填s[n]
s[0] = "";
s[1] = "x";
for (int i = n; i >= 2; i--) {
s[i] = "x^" + to_string(i);
}
string str;
string new_str;
for (int i = n; i >= 0; i--) {
cin >> str;
if (str == "0") {
continue;//跳出当前循环,进入下一次循环
} else if (i == 0) {//常数项
if (str[0] == '-') {
new_str += str;
} else {
if (str[0] == '+') {
new_str += str;
} else {
new_str += '+' + str;
}
}
} else if (str == "-1" || str == "1" || str == "+1") {//系数为+1/1/-1的情况
if (str == "-1") {
new_str += '-' + s[i];
} else {
new_str += '+' + s[i];
}
} else if (str[0] == '-') { //负数
new_str += str + s[i];
} else { //正数:带正号/不带正号,如+5;-5;
if (str[0] == '+') {
new_str += str + s[i];
} else if (str[0] != '+' ) {
new_str += '+' + str + s[i];
}
}
}
if (new_str.empty()) {//系数全为0
cout << '0' << endl;
} else {
for (int i = 0; i < new_str.length(); i++) {
if (new_str[i] != '+') { //多项式不以'+'开头
cout << new_str.substr(i);
break;
}
}
}
return 0;
}