基本计算器(‘(‘ ‘)‘ ‘+‘ ‘-‘ ‘*‘ ‘/ ‘ 正负数)思路及通用实现整理

本文介绍了一种使用两个栈来解析并计算数学表达式的算法。该算法能够处理包含括号、加减乘除运算及负数的情况,并通过优先级判断进行正确的计算顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	- 使用双栈计算表达式结果(存符号、数字)
		- 空格: 直接忽略
		- ( : 入栈
		- ) : 计算结果直到遇到 ( 
		- 数字: 累计记录当前数字
		- 栈顶运算符优先级高于/同等 当前运算符,就一直弹出
	- 注意事项
		- “-2 + 1”,先在nums栈加上0,防止第一个就是 "-" 
class Solution {
public:
	// 这里最初是预防(-2+1)这种情况的,但在nums栈先加0,(-2+1)和-2+1似乎是没区别了
    void init(string &s) {
        int pos = s.find("(-");
        while(pos != -1) {
            s = s.replace(pos, 2, "(0-");
            pos = s.find("(-");
        }
    }
    Solution() {
        priority_v['+'] = 1;
        priority_v['-'] = 1;
        priority_v['*'] = 2;
        priority_v['/'] = 2;
    }
    inline void cal() {
        double n2 = nums.top(); nums.pop();
        double n1 = nums.top(); nums.pop();
        char ch = ops.top();
        if(ch == '+') {
            nums.push(n1 + n2);
        } else if(ch == '-') {
            nums.push(n1 - n2);
        } else if(ch == '*') {
            nums.push(n1 * n2);
        } else {
            nums.push(n1 / n2);
        }
        ops.pop();
        return;
    }

    double calculate(string &s) {
        //init(s);
        nums.push(0.0);
        LL tmp = 0;
        int f = 0;
        for(const auto &ch : s) {
            if(ch >= '0' && ch <= '9') {
                tmp = tmp * 10LL + static_cast<int>(ch - '0');
                f = 1;
            } else {
                if(ch == ' ') continue;
                if(f) nums.push(tmp);
                tmp = 0;
                f = 0;
                if(ch == '(') {
                    ops.push(ch);
                } else if(ch == ')') {
                    while(!ops.empty() && ops.top() != '(') {
                        cal();
                    }
                    ops.pop();
                } else {    // 运算符号
                    while(!ops.empty() && priority_v[ops.top()] >= priority_v[ch]) {
                        cal();
                    }
                    ops.push(ch);
                }
            }
        }
       
        if(f) nums.push(tmp);
        while(!ops.empty()) {
            cal();
        } 
        return nums.top();
    }
private:
    stack<double>nums;
    stack<char>ops;
    map<char,int>priority_v;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值