Pregunta de entrevista de Salesforce

(phone interview) Using any language, write a basic arithmetic calculator. It should take an input string like "1 + 2 * 3" and return the value of the expression, in this case 7.

Respuesta de la entrevista

Anónimo

7 nov 2017

I broke the problem into two parts, a parse phase and an evaluation phase. The parse phase breaks the string into tokens, however, since I was unfamiliar with the standard way of doing this, which is using regular expressions (and I told my interviewer this), I just made the explicit assumption that the input string separates everything with spaces, and split on those. I was also unsure how to build an abstract syntax tree that preserves order of operations, or PEMDAS, so the interviewer suggested I just build the tree with a left to right precedence. The eval phase just evaluates each node in the tree using the values of its children. I followed this with writing a few test cases.