LeetCode 面试题 16.26. 计算器
将数字保存到栈中
class Solution {
public int calculate(String s) {
Deque<Integer> stack = new LinkedList<Integer>();
char preSign = '+';
int sum = 0;
int num = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if (c == '+' || c == '-' || c == '*' || c == '/' || i == s.length()-1) {
switch(preSign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(stack.pop() / num);
break;
}
preSign = c;
num = 0;
}
}
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}