Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
“3+2*2” = 7
“ 3/2 “ = 1
“ 3+5 / 2 “ = 5
Note: Do not use the eval built-in library function.
解法1:
用一个stack来存储中间结果。遇上×,/的时候计算之前的操作,遇上+/-的时候只有在之前的操作为同一优先级的时候才计算。
写的比较繁琐,不如leetcode上的答案好。答案里不需要有stack, 用一个preVal来记录上一个计算的结果,只有当当前操作为加或者减的时候才需要把上一次更新的结果并入最终的结果。
C++
Java
###解法2: ###
答案来自与leetcode
Java