Meta Interview Question

Write a function that parses a string containing sum and multiplication operations and returns the result

Interview Answer

Anonymous

Nov 27, 2016

public static void main(String[] args) { String exp = "2 + 4 + 1 + 6 + 7"; Stack numbers = new Stack(); Stack ops = new Stack(); StringTokenizer t = new StringTokenizer(exp, " "); while (t.hasMoreTokens()) { String token = t.nextToken(); boolean isNumber = false; int n = 0; try { n = Integer.parseInt(token); isNumber = true; } catch(NumberFormatException e) { } if (isNumber) { numbers.push(n); continue; } //it's an operator if (ops.isEmpty()) { ops.push(token); continue; } while (!ops.isEmpty() && token.equals("+")) { String op = ops.pop(); numbers.push(apply(op, numbers.pop(), numbers.pop())); } ops.push(token); } while (!ops.isEmpty()) { String op = ops.pop(); numbers.push(apply(op, numbers.pop(), numbers.pop())); } System.out.println(numbers.pop()); }

1