题解
2024-11-07 12:42:40
发布于:浙江
1阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> coefficients(n + 1);
for (int i = 0; i <= n; ++i) {
cin >> coefficients[i];
}
string result;
bool isFirstTerm = true; // To manage signs for the first term
for (int i = 0; i <= n; ++i) {
int coeff = coefficients[i];
int degree = n - i;
if (coeff == 0) continue; // Skip zero terms
// Handle sign
if (!isFirstTerm) {
if (coeff > 0) result += "+";
} else {
isFirstTerm = false;
}
// Add coefficient and variable/degree formatting
if (degree == 0) {
result += to_string(coeff); // Constant term
} else if (degree == 1) {
if (coeff == 1) result += "x";
else if (coeff == -1) result += "-x";
else result += to_string(coeff) + "x";
} else {
if (coeff == 1) result += "x^" + to_string(degree);
else if (coeff == -1) result += "-x^" + to_string(degree);
else result += to_string(coeff) + "x^" + to_string(degree);
}
}
cout << result << endl;
return 0;
}
这里空空如也
有帮助,赞一个