第一行输入整数
,表示多项式次数。
第二行输入
个整数
,依次为
次项到
次项(常数项)的系数。
在一行输出格式化后的多项式字符串。
5 100 -1 1 -3 0 10
100x^5-x^4+x^3-3x^2+10
3 -50 0 0 1
-50x^3+1
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取多项式次数
int n = scanner.nextInt();
// 读取系数,顺序是a_n, a_{n-1}, ..., a_0
int[] coefficients = new int[n + 1];
for (int i = 0; i <= n; i++) {
coefficients[i] = scanner.nextInt();
}
scanner.close();
// 构建多项式字符串
StringBuilder result = new StringBuilder();
boolean isFirstTerm = true;
// 从高次到低次处理每一项
for (int i = 0; i <= n; i++) {
int coefficient = coefficients[i];
int degree = n - i; // 当前项的次数
// 系数为0的项完全省略
if (coefficient == 0) {
continue;
}
// 处理符号
if (isFirstTerm) {
// 首项若系数为正,不输出前导"+"
if (coefficient < 0) {
result.append("-");
}
isFirstTerm = false;
} else {
// 后续正系数项前需加"+",负系数项加"-"
if (coefficient > 0) {
result.append("+");
} else {
result.append("-");
}
}
// 处理系数的绝对值
int absCoeff = Math.abs(coefficient);
// 当系数为1或-1且次数≥1时,省略系数的绝对值1
if (!(absCoeff == 1 && degree >= 1)) {
result.append(absCoeff);
}
// 处理变量部分
if (degree > 0) {
result.append("x");
// 次数为1输出"x";次数≥2输出"x^k"
if (degree > 1) {
result.append("^").append(degree);
}
}
// 次数为0仅输出常数,这里不需要额外处理
}
System.out.println(result.toString());
}
}
#include <iostream>
using namespace std;
#include<vector>
int main() {
int n;
cin >> n; //5
vector<string>v;
string Fx;
for (int i = 0; i < n + 1; i++) { //存储系数
string a;
cin >> a;
v.push_back(a);
}
for (int i = 0; i < n; i++) {
if (v[i] == "0") { //系数为零跳过
continue;
}
if (v[i] != "0") {
if (stoi(v[i]) > 0) { //系数大于0
if (stoi(v[i]) == 1) {//系数为1的特殊情况
string x;
if(n-i==1){//次数为1的特殊情况
x = "+x";
}
else{
x = "+x^" + to_string(n - i);
}
Fx += x;
}
else {
string x;
if(n-i==1){
x = "+" + v[i] + "x";
}
else{
x = "+" + v[i] + "x^" + to_string(n - i);
}
Fx += x;
}
}
if (stoi(v[i]) < 0) {
if (stoi(v[i]) == -1) {
string x;
if(n-i==1){
x = "-x" ;
}
else{
x = "-x^" + to_string(n - i);
}
Fx += x;
}
else {
string x;
if(n-i==1){
x = v[i] + "x";
}
else{
x = v[i] + "x^" + to_string(n - i);
}
Fx += x;
}
}
}
}
if (stoi(v[n]) > 0) { //最后0次方的常数单独讨论
Fx += "+" + v[n];
}
if (stoi(v[n]) < 0) {
Fx += v[n];
}
if (Fx[0] == '+') {//删掉开头的多余+
Fx.erase(Fx.begin());
cout << Fx;
} else {
cout << Fx;
}
} #include <climits>
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = n; i >= 0; i--) {
int a;
char k;
cin >> a;
if(a==0) continue;
// 1.加号问题
if(i!=n&&a>0){
cout<<'+';
}
// 2.系数问题
if(i!=0 && (a==-1 || a==1)){
if(a==-1) cout<<'-';
}else{
cout<<a;
}
// 3. 指数问题
if(i==1){
cout<<'x';
}else if(i==0){
}else{
cout<<'x'<<'^'<<i;
}
}
}
// 64 位输出请用 printf("%lld")