基本计算器个人总结通用模板

以牛客华为机试题为例 HJ50 四则运算

#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>

using namespace std;

stack<int> num;
stack<char> op;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};

bool is_digit(char c) {
    return c >= '0' && c <= '9';
}

void eval() {
    auto b = num.top();
    num.pop();
    auto a = num.top();
    num.pop();
    auto c = op.top();
    op.pop();
    int x;
    if (c == '+') x = a + b;
    else if (c == '-') x = a - b;
    else if (c == '*') x = a * b;
    else x = a / b;
    num.push(x);
}

//字符串预处理
string preprocess(string& s) {
    string res;
    for (int i = 0; i < s.size(); i ++) {
        if (s[i] == ' ') continue;
        else if (s[i] == '[' || s[i] == '(' || s[i] == '{') res += '(';
        else if (s[i] == ']' || s[i] == ')' || s[i] == '}') res += ')';
        else res += s[i];
        if (res.back() == '(') {
            //先把空格过滤在判断(是不是挨着正负号了
            int j = i + 1;
            while (j < s.size() && s[j] == ' ') j ++;
            if (!is_digit(s[j])) res += '0';
            i = j - 1;
        }
    }
    return res;
}

int main() {
    string s;
    // cin >> s;//注意cin读入字符串遇到空格或者换行就停止了,所以如果题中给的串包含空格就不能用cin读入
    getline(cin, s);//如果有空格这样读
    s = preprocess(s);
    int n = s.size();
    num.push(0);
    for (int i = 0; i < n; i ++) {
        if (is_digit(s[i])) {
            int j = i, x = 0;
            while (j < n && is_digit(s[j]))
                x = x * 10 + s[j ++] - '0';
            num.push(x);
            i = j - 1;
        } else if (s[i] == '(') op.push(s[i]);
        else if (s[i] == ')') {
            while (op.top() != '(') eval();
            op.pop();
        } else {
            while (op.size() && op.top() != '(' && pr[s[i]] <= pr[op.top()]) eval();
            op.push(s[i]);
        }
    }
    while (op.size()) eval();
    cout << num.top() << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值