LeetCode刷题实战227:基本计算器 II
共 3305字,需浏览 7分钟
·
2021-04-02 13:56
Given a string s which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
示例
示例 1:
输入:s = "3+2*2"
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5
解题
class Solution {
public int calculate(String s) {
int result=0,len=s.length(),num=0;
char op='+'; //初始上一个运算符为加法 上个数字为0
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<len;i++){
char c=s.charAt(i);
if(c>='0'){
num=num*10+s.charAt(i)-'0';
}
if(c<'0'&&c!=' '||i==len-1){
if(op=='+') stack.push(num);
if(op=='-') stack.push(-num);
if(op=='*'||op=='/'){
int temp=(op=='*')?stack.pop()*num:stack.pop()/num;
stack.push(temp);
}
op=s.charAt(i);
num=0;
}
}
while(!stack.isEmpty()){
result+=stack.pop();
}
return result;
}
}