call(back)
Algorithms & Data StructuresmediumSign in to star problems

Basic Calculator II

Evaluate an expression of non-negative integers, + - * / and spaces, with normal precedence and integer division truncating toward zero. No parentheses, no unary operators; the result fits in a 32-bit integer.

calculate("3+2*2")      ->  7
calculate(" 3/2 ")      ->  1
calculate(" 3+5 / 2 ")  ->  5
calculate("1-7/2")      ->  -2      // -7/2 truncates to -3, not -4

Hints

Hint 1

Scan once, building the current number digit by digit. When an operator (or the end) arrives, apply the previous operator: push the number for +, its negation for -, and for * or / pop the last term and push the product or quotient.

Hint 2

The answer is the sum of the stack. Division must truncate toward zero: floor division gives the wrong sign for negative terms, so truncate explicitly.

Asked at