题目描述
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.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
思路:
1.遇到数字,则计算出数字结果即可 2.遇到四目运算符,则判断前一个四目运算符是什么,若是+号,则将当前num保存的数*1压入栈中。若为-,num*(-1)压入栈。 若是*号,则将当前num保存的数乘以栈顶元素的结果压入栈中。同理,若为负号,则将当前数除栈顶元素的结果压入栈。 3.若是算数表达式的最后一个字符,则也需要判断它前面的符号,来进行运算。
实现:
private int calculate(String s){
Stack<Integer> st=new Stack<>();
int ret=0,num=0;
char pre='+';//记录上一个符号
s=s.replace(" ","");
for (int i = 0; i <s.length() ; i++) {
if(s.charAt(i)>='0'&&s.charAt(i)<='9'){
num=s.charAt(i)-'0';
}
if(s.charAt(i)<'0'||i==s.length()-1){
switch (pre){
case '+':
st.push(num);
break;
case '-':
st.push(-num);
break;
case '*':
st.push(num*st.pop());
break;
case '/':
st.push(st.pop()/num);
}
num=0;//重新加数,记录符号位
pre=s.charAt(i);
}
}
while(!st.isEmpty()){
ret+=st.pop();
}
return ret;
}