[ITint5] Evaluate Arithmetic Expressions

http://www.itint5.com/oj/#26

Evaluate an arithmetic expression. For simplicity, the following assumptions are made:
  1. There are only positive integers.
  2. There is no overflow. 
  3. Only plus, minus, and multiply operations are supported. No parenthesis, divide, and modulo.
  4. All inputs are valid arithmetic expressions.
Example:
Input: 1+4*3-5
Output: 8
Input: 2-3-5*2
Output: -11

Note that multiplication has higher priority than plus and minus. Every time we meet a '*', we will calculate the number. If we meet a '+' or '-', we will call the recursion, or push the number into a data structure.

Recursive version:
Note that for minus operations, instead of using prevNum - calc(expr, currNum, pos), we need to convert it to negative number (i.e., prevNum + calc(expr, -currNum, pos)). Otherwise the result will be incorrect. For example, 5-4+2, if we use the first approach, the result will be 5-(4+2)=-1. However, it should be 5+(-4+2)=3.
Iterative version (needed to be optimized.):
Here we use a deque. The reason is, for plus and minus, we need to calculate from left to right, i.e., we need to get the numbers from the front. But for multiplication we need to get the numbers from the back. We could also use a stack; in that case, we need to convert minus operation to plus a negative number, similar to what we did in recursive version.

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design