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
1
u/taterNuts Dec 19 '15
This is definitely not something you should have to solve in an interview. In any case, I can give two examples of this - a simple one that I did that isn't hard to break (that maybe you can whip out in an interview), then one that's actually good written by someone who knows what they are doing (modified from a stack overflow answer that was incorrect in some places) and heavily commented that you would not be able to write in an interview.
Simple: https://gist.github.com/Robert-Wett/12895f21fd37f475c0ed
More complex/robust: https://gist.github.com/Robert-Wett/21937475655e9d569364
1
u/parlezmoose Dec 19 '15
Is order of operations important?
1
u/hutsboR Dec 20 '15
This is probably simple enough to tokenize with a regular expression. If not, write a little state machine. Shunting-yard to convert infix notation to postfix notation. Evaluate the postfix expression with a couple stacks. Still quite involved but possibly slightly less so than writing a recursive descent parser?
0
u/zertech Dec 18 '15
Need to parse and tokenize the string using recursive decent based off of a bnf tree, than procrss the toeknized string snd print output.
This is no small piece of code.