Search code examples
javapolynomialsexponentcoefficients

How do I get the coefficients and exponents from a polynomial string?


I am trying to extract coefficients and exponents from a Polynomial string and then storing them to an array so that I could use those arrays to create a new term to which I can do math operations on (e.g add, subtract, and multiply)

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]);
}

Problem is, I really don't know how to do it. I've tried so many ways and it all led to an error..


Solution

  • I would try splitting the poly string using the "+" or "-" chars. If there is a regex split method in java, that would be suitable.

    The array resulting from this split is what should be iterated over in your loop in order to populate the poly List.

    Another thing to be mindful of is the "-2" term in your polynomial, which is technically x^0 and any "ax" terms, which are x^1.