227. Basic Calculator II LeetCode

本文详细解读了一个使用栈实现的计算器算法,通过代码演示如何处理加减乘除运算符,解决数字间的运算顺序问题。

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

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

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值