You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java实现多项式加法?我在实现时遇到困难

多项式加法实现思路与步骤

步骤1:解析多项式字符串为字典

先把输入的多项式字符串拆成单个项,再提取每个项的系数和指数,用指数为键、系数为值的字典存储,方便后续合并计算。

比如处理 "2x^3 + 3x^2 + 2":

  • 拆分项:["2x^3", "3x^2", "2"]
  • 逐个解析:
    • "2x^3" → 指数3,系数2 → {3:2}
    • "3x^2" → 指数2,系数3 → {2:3}
    • "2" → 指数0(常数项),系数2 → {0:2}

示例代码(Python):

def parse_poly(poly_str):
    terms = poly_str.replace(" ", "").split("+")
    poly_dict = {}
    for term in terms:
        if "x^" in term:
            coeff_part, exp_part = term.split("x^")
            coeff = int(coeff_part) if coeff_part else 1  # 处理x^3这种系数为1的情况
            exp = int(exp_part)
        elif "x" in term:
            coeff_part = term.replace("x", "")
            coeff = int(coeff_part) if coeff_part else 1
            exp = 1
        else:
            coeff = int(term)
            exp = 0
        poly_dict[exp] = poly_dict.get(exp, 0) + coeff
    return poly_dict

步骤2:合并两个多项式字典

把两个解析后的字典合并,相同指数的系数直接相加,不同指数的项直接保留。

示例代码:

def add_polys(poly1_dict, poly2_dict):
    combined = poly1_dict.copy()
    for exp, coeff in poly2_dict.items():
        combined[exp] = combined.get(exp, 0) + coeff
    return combined

步骤3:将合并后的字典转换为多项式字符串

按指数从高到低排序,把每个键值对转换成规范的项字符串,最后拼接成结果。需要处理几种特殊情况:

  • 系数为1且指数≠0时,省略系数(比如1x^3 → x^3)
  • 指数为1时,省略1(比如2x1 → 2x)
  • 指数为0时,只保留系数(常数项)
  • 系数为0的项直接跳过

示例代码:

def dict_to_poly(poly_dict):
    sorted_terms = sorted(poly_dict.items(), key=lambda x: -x[0])
    poly_terms = []
    for exp, coeff in sorted_terms:
        if coeff == 0:
            continue
        coeff_str = str(coeff) if abs(coeff) != 1 or exp == 0 else ("" if coeff == 1 else "-")
        if exp == 0:
            term = coeff_str
        elif exp == 1:
            term = f"{coeff_str}x"
        else:
            term = f"{coeff_str}x^{exp}"
        poly_terms.append(term)
    return " + ".join(poly_terms)

完整调用示例

poly1 = "2x^3 + 3x^2 + 2"
poly2 = "2x^2 + 6"

p1 = parse_poly(poly1)
p2 = parse_poly(poly2)
combined = add_polys(p1, p2)
result = dict_to_poly(combined)
print(result)  # 输出:2x^3 + 5x^2 + 8

内容的提问来源于stack exchange,提问作者joshxb2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:01:02