227. Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string contains onlynon-negativeintegers,+,-,*,/operators and empty spaces. The integer division should truncate toward zero.

Example 1:

Input: 
"3+2*2"

Output: 7

Example 2:

Input: " 3/2 "

Output:1

Example 3:

Input:" 3+5 / 2 "

Output: 5

Note:

  • You may assume that the given expression is always valid.

  • Do not use the evalbuilt-in library function.

Thoughts: need to look back to know what is the operand value when encountered an operator. Hence need two variable: operator and operand.

  1. With stack: using a stack to keep track of numbers and do the operation based on operators.

  2. Without stack: only add current operand to the accumulative sum when encountered '+' or '-' since '*' and '/' has prioirty

Code: with a stack

Code: without a stack

Last updated

Was this helpful?