This question already has an answer here:
- Advanced Calculator 6 answers
Given a string representing a mathematical expression return the result
A string representing a mathematical expression :
'1 + 2 - 3 * (2/3 * 1)'.
The result after performing all operations.
+ ---> plus - ---> minus * ---> multiplication / ---> division ( ---> opening parenthesis ) ---> closing parenthesis
operator precedence :
Operators are always evaluated from
from here ---> there, and
* and / must be evaluated before
+ and -
Parenthesis take precedence over everything else and must be completed before all.
You should be able to support multiple(nested) levels of parenthesis.
1 - ( 2 * ( 3 / 9 + ( 2 * 6 ) ) )
White space :
Whitespace doesn't matter, you can have whitespace between operators or you can't (Consistency is required though)
Given input will always be valid. It will consist of nothing except
- Numbers (
0-9) of arbitary length
- operators (
+ , - , * , /)
- parenthesis (
( / )) nested
- white space (
optional with consistency)
- Numbers (
Functionor their equivalent counter-parts in any language is forbidden
- using built-in functions designed specifically for this is also forbidden
- all standard loopholes are forbidden by default.
- You need to support floats to a reasonably high value (depending on the language) but after that integers will work. alternately after that floating point error (if reasonable) will be acceptable.
- This is code-golf so shortest code in bytes for each language wins.
1 + 2 * 3 ---> 7 10 * 2 / (2 - 3) * 2 ---> -10 (expression is (2*10) / ((2-3)*2) => 20/-2 1-(2*(3/9+(2*6)-3)) ---> -53/3 (3/9 is the fraction and not the whole) -1 * --10 ---> -10 (support for unary minus)