Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack.

Problem: Evaluate an expression with +, −, *, / (integer division truncating toward zero) and no parentheses, using a stack.
def calc(s):
    st, num, op = [], 0, '+'
    for i, c in enumerate(s + '+'):
        if c.isdigit(): num = num * 10 + int(c)
        elif c in '+-*/':
            if op == '+': st.append(num)
            elif op == '-': st.append(-num)
            elif op == '*': st.append(st.pop() * num)
            else: st.append(int(st.pop() / num))
            op, num = c, 0
    return sum(st)
print(calc("3+5/2*4-6/4"), calc("14-3*2/4"))
What is printed?
  1. A. 11 11
  2. B. 10 13
  3. C. 10 12
  4. D. 4 13

Correct answer: B. 10 13

* and / are applied immediately to the top of the stack, + and − only push signed terms. 3 + (5/2 = 2)·4 − (6/4 = 1) = 3 + 8 − 1 = 10; 14 − (3·2 = 6)/4 → 14 − 1 = 13, since −6/4 truncates to −1 (floor division would give −2 and 12).

More Coding Interview Problems questions

Exams that ask this topic