Basic Calculator II

本文介绍了一个简单的表达式计算器实现,该计算器能解析并计算包含基本算术运算符(加、减、乘、除)及非负整数的表达式字符串。文章通过一个具体的C++实现案例,展示了如何逐字符解析输入字符串,并利用栈来处理运算符优先级,最终返回表达式的计算结果。

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

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces. The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5


#include<algorithm>
#include<string>
#include<stack>
class Solution {
    stack<int> st;
    string str;
    int i;

public:
    int calculate(string s) {
        i = 0;
        str = s;


        while(i<str.size ()){
            char c = str[i];
            if(isspace (c)){
                ++i;
                continue;
            }

            if(isdigit (c)){
                int v = getInt ();
                st.push (v);
                continue;
            }

            if(isoperator (c)){
                if(c == '*'){
                    ++i;
                    int v = getInt ();
                    int v1 = st.top ();
                    st.pop ();
                    v1 *= v;
                    st.push (v1);
                    continue;
                }

                if(c == '/'){
                    ++i;
                    int v = getInt ();
                    int v1 = st.top ();
                    st.pop ();
                    v1 /= v;
                    st.push (v1);
                    continue;

                }

                if(c == '-'){
                    ++i;
                    int v = getInt ();
                    st.push (-1 * v);
                    continue;
                }

                if(c == '+'){
                    ++i;
                    int v = getInt ();
                    st.push ( v);
                    continue;

                }
            }

        }


        int ret = 0;
        while(!st.empty ()){
            ret += st.top ();
            st.pop ();
        }

        return ret;
    }

    bool isoperator(char c){
        return c == '+' || c =='-' || c == '*' || c == '/';
    }

    int getInt(){
        string res;
        while(i<str.size ()){
            char c = str[i];
            if(isspace (c))
                ++i;
            else if(isoperator (c))
                break;
            else if(isdigit (c)){
                res.push_back (c);
                ++i;
            }
        }

        return atoi (res.data ());
    }
};

简单的加减剩除计算器:

1.先读一个数,入栈

2.A读一个符号,如果读到 ‘*’ 或 ‘/’ ,一个数出栈,继续在字符串里读一个数,两个数做相应的'*' 或'/', 压入栈。

2.B,如果这个符号是+, 再读一个数直接入栈,如果是-号,则转为负数再入栈。

3.最后对栈里的所有数做加法,返回结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值