r/csinterviewproblems • u/pxdra • Dec 18 '15
Evaluate Math Expression
As mentioned in title.
You're given a math expression in a string, return the result as an int.
Example: "10+2*3-5/2" -> 14.
Basic: four basic operations, +-*/ Bonus: parenthesis, power.
7
Upvotes
View all comments
Show parent comment
1
u/rcheu Dec 18 '15 edited Dec 18 '15
In JS:
var calc = function(s) { return eval(s);}.
More seriously, one fast way to do just operators is to do two passes from left to right, one where you reduce multiplication and division, and then a second to do addition/subtraction. Extending this to parentheses would be a fast jump from there as well, just add recursion when hitting an open paren with a first initial pass.
One technique for approaching complex problems like this is to think of how you would do it on paper. On paper we don't do a recursive descent and make a big tree. We just follow the rules--do multiplication and division from left to right and replace with results by crossing out and writing above, then do addition/subtraction.