Microsoft Interview Question
1,056 Interview Reviews |
Back to all Microsoft Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Microsoft:
How to write an evaluator for a string like "(1+3 * ( 5 / 4)) and get a numeric result.
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (3)
2 of 2 people found this helpful
Use two stacks: an operator stack, and an operand stack. Alternate between parsing operands and operators, pushing onto the appropriate stack as you go. Whenever you encounter an operator that has precedence less than or equal to the operator at the top of the operator stack, pop that operator and the topmost two operands, evaluate, and push the result onto the operand stack. You can treat the "end of string" as though it were an operator of the lowest precedence. When you are done, the operator stack should be empty, and the operand stack should contain one element, the result.
To handle parentheses, treat the left paren as though it were an operator, except that you'll always push it immediately without evaluating anything. Then treat the left paren as though it were an operator of the lowest precedence. This forces you to evaluate only within that paren group until you encounter its corresponding right paren, at which point you'll pop and evaluate until you get to the left paren.
Helpful Answer?
Yes |
No
Inappropriate?
eval_atom:
if (next is number): consume and return number
if (next is '(': consume and return eval_expr(), consume ')' and return the result
eval_mul:
result = eval_atom()
while (next is '*' or '/') consume, result = result * (or /) eval_atom() - depending of the operator
return result
eval_expr:
result = eval_mul
while (next is '+' or '-') consume, result = result + (or -) eval_mul() - depending of the operator
return result
Above represents parsing grammar:
expr: expr_mul | expr_mul ('+' | '-') expr
expr_mul: atom | atom ('*' | '/') expr_mul
atom: integer | '(' expr ')'
Helpful Answer?
Yes |
No
Inappropriate?
Members can
answer or comment on this question
–
Join Now (It's Free) or
Sign In



0 of 0 people found this helpful
by Praful Rana: