The above option is correct, but it will be very cumbersome and buggy. Consider the case 2*-(1+2)^-(2+5*-(2+4)) . As you can see, you need to consider many things. Also, when you find "* - (" for example, you know that you replace it with * (0 - (....), which will be encoded in a cumbersome recursive function. The best solution is much simpler. Consider cases where the operator " - ", and it is preceded by another operator or preceded by a left bracket or when it is the first character of input (these cases mean that it is a unary minus, not binary). In this case, you change it to another character, say" u "( this was my case) and make its priority the same as "^".
In addition, processing it as part of a literal number has its catch. Imagine a case like -2 ^ 4. In Wolfram Alpha, you get -16, not 16.
And consider using stacks. They will make your life easier.
Let me explain what I meant. Note that you are provided with input:
2 / - 7 + (- 9 * 8) * 2 ^ - 9 - 5
Having made the replacement that I proposed, it will look like this:
2 / u 7 + (u 9 * 8) * 2 ^ u 9 - 5
Your operator priority switch should now be changed to:
switch(c) { case '-' : case '+' : return 1 ; case '*' : case '/' : return 2 ; case '^' : case 'u': //note the 'u' operator we added return 3 ; default : return 0 ; }
And, of course, you need to make changes in support of this unary operator.
TGO
source share