Basic calculator (stack)

Title: https://leetcode-cn.com/problems/basic-calculator/
Reference: https://leetcode-cn.com/problems/basic-calculator/solution/lioneycli-yong-zhan-jian-dan-qiu- jie-by-lioney /
Implement a basic calculator to calculate the value of a simple string expression.
String expressions can include left brackets (, right brackets), plus sign +, minus sign-, non-negative integers, and spaces.

class Solution {
public:
    int calculate(string s) {
        int n = s.length();
        long long res = 0,flag = 1,tmp = 0;
        stack<long long> st;
        for(int i = 0;i < n;i++) {
            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();
            }
            else if('0'<=s[i] && s[i]<='9') {
                tmp = 0;
                while(i < n && '0'<=s[i] && s[i]<='9')
                    tmp = tmp*10+s[i]-'0',i++;
                i--;
                res += tmp*flag;
            }
        }
        return res;
    }
};
Published 152 original articles · won praise 2 · Views 6449

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/104938437