美文网首页
Calculator Problem (Leetcode 227

Calculator Problem (Leetcode 227

作者: stepsma | 来源:发表于2016-11-07 01:03 被阅读0次

calculator会想到stack,不同题目的处理方式不一样
227 Basic Calculator II

class Solution {
public:
    int calculate(string s) {
        if(s.empty()) return 0;
        stack<int> st;
        char sign = '+';
        int cur = 0;
        for(int i=0; i<s.length(); i++){
            if(isdigit(s[i])){
                cur = cur*10 + s[i]-'0';
            }
            if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || i == s.length()-1){
                if(sign == '+') st.push(cur);
                if(sign == '-') st.push((-1)*cur);
                if(sign == '*'){
                    int a1 = st.top(); st.pop();
                    st.push(a1 * cur);
                }
                if(sign == '/'){
                    int a1 = st.top(); st.pop();
                    st.push(a1 / cur);
                }
                cur = 0;
                if(i != s.length()-1) sign = s[i];
                
            }
        }
        int ret = 0;
        while(!st.empty()){
            ret += st.top(); st.pop();
        }
        return ret;
    }
};

Leetcode 150 Evaluate Reverse Polish Notation:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        if(tokens.empty()) return 0;
        stack<int> st;
        for(int i=0; i<tokens.size(); i++){
            if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){
                if(st.empty()) return 0;
                int num1 = st.top(); st.pop();
                if(st.empty()) return 0;
                int num2 = st.top(); st.pop();
                st.push(eval(num1, num2, tokens[i]));
            }else{
                st.push(stoi(tokens[i]));
            }
        }
        return st.top();
    }
    
    int eval(int num1, int num2, string sign){
        if(sign == "+") return num2 + num1;
        else if(sign == "-") return num2 - num1;
        else if(sign == "*") return num2 * num1;
        else return num2 / num1;
    }
};

相关文章

网友评论

      本文标题:Calculator Problem (Leetcode 227

      本文链接:https://www.haomeiwen.com/subject/mnwnuttx.html