问题:
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.
解决:
① 注意优先级问题,由于存在运算优先级,使用一个栈保存数字,如果该数字之前的符号是加或减,那么把当前数字压入栈中,注意如果是减号,则加入当前数字的相反数,因为减法相当于加上一个相反数。如果之前的符号是乘或除,那么从栈顶取出一个数字和当前数字进行乘或除的运算,再把结果压入栈中,那么完成一遍遍历后,所有的乘或除都运算完了,再把栈中所有的数字都加起来就是最终结果了。
class Solution { //26ms
public int calculate(String s) {
int res = 0;
int num = 0;
char sign = '+';
Stack<Integer> nums = new Stack<>();
for (int i = 0;i < s.length();i ++){
char c =s.charAt(i);
if (c >= '0' && c <= '9'){
num = num * 10 + c - '0';
}
if ((c <'0' && c != ' ') || i == s.length() - 1){
if (sign == '+'){
nums.push(num);
}
if (sign == '-'){
nums.push(-num);
}
if (sign == '*' || sign == '/'){
int tmp = sign == '*' ? nums.pop() * num : nums.pop() / num;
nums.push(tmp);
}
sign = c;
num = 0;
}
}
while (! nums.isEmpty()){
res += nums.pop();
}
return res;
}
}
② 在discuss中看到的
class Solution { //17ms
public int calculate(String s) {
int cur = 0, res = 0, prod = 1;
char prevOp = '+';
for (int i = 0; i <= s.length(); i++) {
char c = i < s.length() ? s.charAt(i) : '+';
if (c == ' ') {
continue;
}
else if (c >= '0' && c <= '9') {
cur = cur * 10 + (c - '0');
} else {
int tmp;
if (prevOp == '/') {
tmp = prod / cur;
} else {
tmp = prod * cur;
}
if (c == '+' || c == '-') {
res += tmp;
prod = c == '+' ? 1 : -1;
} else {
prod = tmp;
}
cur = 0;
prevOp = c;
}
}
return res;
}
}