227. Basic Calculator II
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.
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.
Analysis
link:
http://www.cnblogs.com/grandyang/p/4601208.html
https://leetcode.com/problems/basic-calculator-ii/discuss/63003/Share-my-java-solution
由于存在运算优先级,我们采取的措施是使用一个栈保存数字,如果该数字之前的符号是加或减,那么把当前数字压入栈中,注意如果是减号,则加入当前数字的相反数,因为减法相当于加上一个相反数。如果之前的符号是乘或除,那么从栈顶取出一个数字和当前数字进行乘或除的运算,再把结果压入栈中,那么完成一遍遍历后,所有的乘或除都运算完了,再把栈中所有的数字都加起来就是最终结果了
Solution
public int calculate(String s) {
int len;
if (s == null || (len = s.length()) == 0)
return 0;
Deque<Integer> stack = new LinkedList<Integer>();
int num = 0;
char sign = '+';
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
}
if ((!Character.isDigit(s.charAt(i)) && ' ' != s.charAt(i)) || i == len - 1) {
if (sign == '-') {
stack.push(-num);
}
if (sign == '+') {
stack.push(num);
}
if (sign == '*') {
stack.push(stack.pop() * num);
}
if (sign == '/') {
stack.push(stack.pop() / num);
}
sign = s.charAt(i);
num = 0;
}
}
int re = 0;
for (int i : stack) {
re += i;
}
return re;
}