1. 程式人生 > >leetcode 224. Basic Calculator 、227. Basic Calculator II

leetcode 224. Basic Calculator 、227. Basic Calculator II

+= ack col 遇到 amp 數值 nbsp basic 符號位

這種題都要設置一個符號位的變量

224. Basic Calculator

設置數值和符號兩個變量,遇到左括號將數值和符號加進棧中

class Solution {
public:
    int calculate(string s) {
        stack<int> st;
        int res = 0,flag = 1;
        for(int i = 0;i < s.size();i++){
            if(s[i] >= 0 && s[i] <= 9){
                
int num = 0; while(i < s.size() && s[i] >= 0 && s[i] <= 9){ num = num*10 + flag * (s[i] - 0); i++; } res += num; i--; } else if(s[i] ==
+) flag = 1; else if(s[i] == -) flag = -1; else if(s[i] == (){ st.push(res); st.push(flag); res = 0,flag = 1; } else if(s[i] == )){ res *= st.top(); st.pop(); res
+= st.top(); st.pop(); } } return res; } };

227. Basic Calculator II

乘除法有優先級,這個時候需要將這些數值彈出

class Solution {
public:
    int calculate(string s) {
        long res = 0,num = 0;
        char op = +;
        stack<int> st;
        for(int i = 0;i < s.size();i++){
            if(s[i] >= 0 && s[i] <= 9)
                num = num * 10 + s[i] - 0;
            if(s[i] == + || s[i] == - || s[i] == * || s[i] == / || i == s.size() - 1){
                if(op == +)
                    st.push(num);
                if(op == -)
                    st.push(-num);
                if(op == * || op == /){
                    int tmp = op == * ? st.top() * num : st.top() / num;
                    st.pop();
                    st.push(tmp);
                }
                op = s[i]; 
                num = 0;
            }
        }
        while(!st.empty()){
            res += st.top();
            st.pop();
        }
        return res;
    }
};

leetcode 224. Basic Calculator 、227. Basic Calculator II