多项式输出
思路
拿到这题先想一下:给你一个一元 n 次多项式的系数,要你按标准数学格式输出,听起来简单对吧?但实际上坑还挺多的——符号怎么处理?系数为 1 或 -1 怎么办?系数为 0 的项要跳过?首项和后续项的符号规则不一样?
别急,我们一个个捋清楚。
每一项需要考虑什么?
对于第 i 个系数(对应次数为 n-i 的项),输出时要处理三件事:符号、系数绝对值、变量部分。
符号规则:
- 如果是首个非零项(首项):正数不输出
+,负数输出- - 如果不是首项:正数前面加
+,负数前面加-
系数绝对值规则:
- 如果当前项是常数项(次数为 0):直接输出绝对值
- 如果当前项次数 >= 1 且绝对值为 1:省略不写(比如
x^3而不是1x^3) - 其他情况正常输出绝对值
变量部分规则:
- 次数为 0:不输出 x
- 次数为 1:输出
x - 次数 >= 2:输出
x^次数
核心逻辑
遍历所有系数,跳过为 0 的项,用一个 first 标记判断当前是不是首个输出项,然后按上面三条规则拼接字符串就行了。
整个过程就是纯模拟,没有什么算法技巧,考的就是你对细节的把控能力。
代码
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 0; i <= n; i++) cin >> a[i];
bool first = true;
bool hasOutput = false;
for (int i = 0; i <= n; i++) {
int coef = a[i];
int power = n - i; // 当前项的次数
if (coef == 0) continue;
// 符号处理
if (first) {
if (coef < 0) cout << "-";
} else {
if (coef > 0) cout << "+";
else cout << "-";
}
int absCoef = abs(coef);
if (power == 0) {
// 常数项,直接输出绝对值
cout << absCoef;
} else {
// 非常数项,系数绝对值为1时省略
if (absCoef != 1) cout << absCoef;
if (power == 1) cout << "x";
else cout << "x^" << power;
}
first = false;
hasOutput = true;
}
if (!hasOutput) cout << "0";
cout << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n + 1];
for (int i = 0; i <= n; i++) a[i] = sc.nextInt();
StringBuilder sb = new StringBuilder();
boolean first = true;
for (int i = 0; i <= n; i++) {
int coef = a[i];
int power = n - i;
if (coef == 0) continue;
// 符号处理
if (first) {
if (coef < 0) sb.append("-");
} else {
if (coef > 0) sb.append("+");
else sb.append("-");
}
int absCoef = Math.abs(coef);
if (power == 0) {
sb.append(absCoef);
} else {
if (absCoef != 1) sb.append(absCoef);
if (power == 1) sb.append("x");
else sb.append("x^").append(power);
}
first = false;
}
if (sb.length() == 0) sb.append("0");
System.out.println(sb.toString());
}
}
n = int(input())
a = list(map(int, input().split()))
result = []
first = True
for i in range(n + 1):
coef = a[i]
power = n - i
if coef == 0:
continue
# 符号处理
if first:
if coef < 0:
result.append("-")
else:
if coef > 0:
result.append("+")
else:
result.append("-")
abs_coef = abs(coef)
if power == 0:
result.append(str(abs_coef))
else:
if abs_coef != 1:
result.append(str(abs_coef))
if power == 1:
result.append("x")
else:
result.append("x^" + str(power))
first = False
if not result:
print("0")
else:
print("".join(result))
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => lines.push(line));
rl.on('close', () => {
const n = parseInt(lines[0]);
const a = lines[1].split(' ').map(Number);
let result = [];
let first = true;
for (let i = 0; i <= n; i++) {
const coef = a[i];
const power = n - i;
if (coef === 0) continue;
if (first) {
if (coef < 0) result.push("-");
} else {
if (coef > 0) result.push("+");
else result.push("-");
}
const absCoef = Math.abs(coef);
if (power === 0) {
result.push(absCoef.toString());
} else {
if (absCoef !== 1) result.push(absCoef.toString());
if (power === 1) result.push("x");
else result.push("x^" + power);
}
first = false;
}
if (result.length === 0) console.log("0");
else console.log(result.join(""));
});
复杂度分析
- 时间复杂度:
,遍历一遍系数数组
- 空间复杂度:
,存储系数数组
总结
这道题没有什么高深的算法,就是字符串模拟。但模拟题最容易翻车的地方就在细节——首项不加正号、系数为 1 时省略、系数为 0 跳过、常数项和非常数项的输出区别……把这些边界情况一条一条列清楚,代码自然就写出来了。写这类题的诀窍就是:别想着一步到位,先把规则拆解成独立的小问题,逐个击破。



京公网安备 11010502036488号