227 - Basic Calculator II

解法一 - Stack

這題的關鍵就是要用 stack,另外因為第一個數一定要放進 stack,所以一開始會把 sign 設成 '+'。

class Solution {
public:
    int calculate(string s) {
        int len = s.length();
        if(len == 0) { 
            return 0;
        }

        stack<int> st;
        int num = 0;
        char sign = '+';
        for(int i = 0; i < len; ++i) {
            if(isdigit(s[i])) {
                num = num * 10 + (s[i] - '0');
            }

            if( (!isdigit(s[i]) && s[i] != ' ') || i == len - 1) {
                if(sign == '+') { st.push(num); }
                else if(sign == '-') { st.push(-num); }
                else if(sign == '*') { 
                    int tmp = st.top() * num; 
                    st.pop();
                    st.push(tmp);
                }
                else if(sign == '/') {
                    int tmp = st.top() / num; 
                    st.pop();
                    st.push(tmp);
                }

                sign = s[i];
                num = 0;
            }
        }

        int res = 0;
        while(!st.empty()) {
            res += st.top();
            st.pop();
        }

        return res;
    }
};

results matching ""

    No results matching ""