java - 如何从多项式字符串中获取系数和指数?

标签 java polynomials exponent coefficients

我正在尝试从多项式字符串中提取系数和指数,然后将它们存储到一个数组中,以便我可以使用这些数组创建一个新项,我可以对其进行数学运算(例如加、减和乘) )

List<Term> poly = new ArrayList<>;
String poly = "26x^7+5x^6-8x^3-2";

int[] coeff = // Something like using split method here to get coeffs
int[] expo = // Same here but with exponents

for(int i = 0; i < coeffs.length; i++){
    poly.add(new Term(coeff[i], expo[i]);
}

问题是,我真的不知道该怎么做。我尝试了很多方法,但都导致错误..

最佳答案

这是一个忽略 x^1 和 x^0 以及系数=1 的额外复杂性的解决方案。

它在正则表达式中使用 Lookahead,如所述 here

import java.util.ArrayList;
import java.util.List;

public class MyClass {

    public static void main(String[] args) {
        // expect format ax^n for each term. in particular in the cases a=1, x=1 and x=0.
        String poly = "26x^7+5x^6-8x^3+1x^1-2x^0";

        // remove ^ and then split by x and by + and - keeping the sign
        String[] numbers = poly.replace("^", "").split("((?=\\+)|(?=\\-)|x)");

        List<Integer> coeff = new ArrayList<>();
        List<Integer> expo = new ArrayList<>();

        // we can now assume that for every coefficient there is an exponent
        for (int i = 0; i < numbers.length; i += 2) {
            coeff.add(Integer.parseInt(numbers[i]));
            expo.add(Integer.parseInt(numbers[i + 1]));
        }

        System.out.println(coeff);
        System.out.println(expo);
    }
}

输出:

[26, 5, -8, 1, -2]
[7, 6, 3, 1, 0]

关于java - 如何从多项式字符串中获取系数和指数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56041285/

相关文章:

java - 使用堆栈检查分隔符

java - Jfugue 中的乐器没有变化

R 找到最近凸曲线 "below"的一组点

Python 多项式根不准确

algorithm - 矩阵幂和

java - Struts 2 中的页面加载操作和表单操作

java - 使用内存中的 CSV 数据源生成 Jasper 报告报告

algorithm - 是否有一种快速算法来确定充满变量的矩阵的行列式?

java - 计算一个数的幂;重复的话