實現一個基本的計算器來計算一個簡單的字符串表達式的值。
字符串表達式僅包含非負整數,+, - ,*,/ 四種運算符和空格 。 整數除法僅保留整數部分。
示例 1:
輸入: "3+2*2"
輸出: 7
示例 2:
輸入: " 3/2 "
輸出: 1
示例 3:
輸入: " 3+5 / 2 "
輸出: 5
說明:
你可以假設所給定的表達式都是有效的。
請不要使用內置的庫函數 eval。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/basic-calculator-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution {
int start = 0;
public int calculate(String s) {
//遇到優先級高的先入棧,計算優先級高的
Stack<Integer> st = new Stack<>();//操作數棧
Stack<Character> op = new Stack<>();//操作符棧
start = 0;
while(start<s.length()){
if(s.charAt(start)==' '){//空格
start++;
}else if(s.charAt(start)=='+' || s.charAt(start)=='-' || s.charAt(start)=='*' || s.charAt(start)=='/'){
//遇到運算符入棧
op.push(s.charAt(start++));
}else{
int cur = getNum(s, start);//獲取當前數字
if(!op.empty() && (op.peek()=='*' || op.peek()=='/')){//只計算乘除
char ch = op.pop();
int last = st.pop();
if(ch == '*'){
cur *= last;
}else if(ch == '/'){
cur = last/cur;
}
}
st.push(cur);
}
}
int ret = 0;
while(!op.empty()){//計算加減,減在對應數字上取負
char ch = op.pop();
int last = st.pop();
if(ch == '-'){
ret += (-last);
}else{
ret += last;
}
}
ret += (st.pop());//剩餘第一個正數
return ret;
}
int getNum(String s, int index){
//截取一段連續的數字
int i=index+1;
for(; i<s.length() ; i++){
int tmp = s.charAt(i)-'0';
if(tmp>9 || tmp<0){
break;
}
}
int ret = Integer.valueOf(s.substring(index,i));
start = i;
return ret;
}
}