Frage

In JAVA:-

Given an equation in a string: String equation = "4*x^3-19*x^2+2*x-1=0";, how to find its degree?

I thought of looping through the string finding positions of carets'^', get the numbers after the carets and the highest among them would be the degree of the equation. But what if the numbers are more than a single digit? Implementing this would be designing a parser of equations!

So can you tell me any other way?

Edit:

I'd like to know the way it can be done, for example using regular expressions as stated in one of the comments and not the code.

War es hilfreich?

Lösung

You can try something like this:

int degree = 1;
Matcher m = Pattern.compile("(?<=\\^)\\d+").matcher(equation);

while (m.find()) {
    int exp = Integer.parseInt(m.group());

    if (exp > degree)
        degree = exp;
}

We're finding all matches of (?<=\^)\d+. \d+ matches a string of 1 or more digits, and (?<=\^) is a positive lookbehind to ensure that these digits are preceded by a caret (but does not include this caret in the match).

Andere Tipps

You could use the following Regular Expression to match the values that are contained after a caret :

\^\d+

Which would explicitly match each value and then you could simply find the largest value that was matched and return it.

(Tutorial on Regular Expressions in Java)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top