题目链接:https://leetcode-cn.com/problems/basic-calculator-ii/description/
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式仅包含非负整数,+
, -
,*
,/
四种运算符和空格
。 整数除法仅保留整数部分。
示例 1:
输入: "3+2*2"
输出: 7
示例 2:
输入: " 3/2 "
输出: 1
示例 3:
输入: " 3+5 / 2 "
输出: 5
说明:
你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。
思路:利用栈的方式解决运算优先级的问题 当为加减时放入栈中 当为乘除时讲栈顶元素与最近获得一个数进行运算
因为所有输入都是合法的 所有我们预存上一个运算符和数字 这样简便操作
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;
}
}