227. Basic Calculator II LeetCode

来源:互联网 发布:格式化数据恢复 编辑:程序博客网 时间:2024/05/20 21:44

题意:模拟一个计算器的+-*/,数字只会出现正整数。
题解:用栈模拟即可,代码恶心了点。

class Solution {public:    int calculate(string s) {        stack<int> sta;        char op = '+';        int ans = 0,tmp = 0;        for(int i = 0; i < s.length(); i++)        {            if(isdigit(s[i]))                tmp = tmp * 10 + s[i] - '0';            if (!isdigit(s[i]) && !isspace(s[i]) || i == s.size()-1)            {                if(op == '+')                    sta.push(tmp);                else if(op == '-')                    sta.push(-tmp);                else if(op == '*')                {                    int num = sta.top() * tmp;                    sta.pop();                    sta.push(num);                }                else                {                    int num = sta.top() / tmp;                    sta.pop();                    sta.push(num);                }                tmp = 0;                op = s[i];            }        }        while(!sta.empty())        {            ans += sta.top();            sta.pop();        }        return ans;    }};
0 0