C++ extract polynomial coefficients

前端 未结 5 1336
迷失自我
迷失自我 2021-01-26 01:38

So I have a polynomial that looks like this: -4x^0 + x^1 + 4x^3 - 3x^4
I can tokenize this by space and \'+\' into: -4x^0, x^1, 4x^3, -, 3x^4

How could I just get t

5条回答
  •  温柔的废话
    2021-01-26 02:03

    Start with "-4x^0 + x^1 + 4x^3 - 3x^4"
    Split after ^number: "-4x^0", " + x^1", " + 4x^3", " - 3x^4"
    Now everything behind an ^ is an exponent, everything before the x is an coefficient
    

    EDIT: Simple method to get the coefficient (including the sign):

    Init coefficient with 0, sign with '+'
    Go through each character before the x from left to right
      If it's a number ('0'..'9'), coefficient = coefficient * 10 + number
      If it's '-', set sign to '-'
    

提交回复
热议问题