Leetcode 227. Basic Calculator II
题目
Input: "3+2*2"
Output: 7Input: " 3/2 "
Output: 1Input: " 3+5 / 2 "
Output: 5思路
解答
Complexity Analysis
拓展
总结
Reference
Last updated
Input: "3+2*2"
Output: 7Input: " 3/2 "
Output: 1Input: " 3+5 / 2 "
Output: 5Last updated
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
int operand = 0;
int prev_op = '+';
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
// Covert digits to number (e.g. operand = 12, string = "123" -> 12 * 10 + 3)
if (Character.isDigit(ch)) {
operand = operand * 10 + Character.getNumericValue(ch);
}
// Meet new operator or end of string: end of current operand
if ( (!Character.isDigit(ch) && ch != ' ') || i == s.length() - 1) {
switch(prev_op) {
// additon and subtraction only stores the values for later uses
case '+':
stack.push(operand);
break;
case '-':
stack.push(operand * -1);
break;
// perform the multiplication and division right now and store result
case '*':
stack.push(stack.pop() * operand);
break;
case '/':
stack.push(stack.pop() / operand);
break;
}
operand = 0;
prev_op = ch;
}
}
// Sum up all remaining numbers in stack.
int res = 0;
for (Integer num : stack) {
res += num;
}
return res;
}
}