C++ extract polynomial coefficients

前端 未结 5 1443
迷失自我
迷失自我 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:28

    Once you have tokenized to "-4x^0", "x^1", etc. you can use strtol() to convert the textual representation into a number. strtol will automatically stop at the first non-digit character so the 'x' will stop it; strtol will give you a pointer to the character that stoped it, so if you want to be paranoid, you can verify the character is an x.

    You will need to treat implicit 1's (i.e. in "x^1" specially). I would do something like this:

    long coeff;
    if (*token == 'x')
    {
       coeff = 1;
    }
    else
    {
        char *endptr;
        coeff = strtol(token, &endptr, 10);
        if (*endptr != 'x')
        {
            // bad token
        }  
    }
    

提交回复
热议问题