HJ54 表达式求值

描述
给定一个字符串描述的算术表达式,计算出结果值。
输入字符串长度不超过 100 ,合法的字符包括 ”+, -, *, /, (, )” , ”0-9” 。
数据范围:运算过程中和最终结果均满足

#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
using namespace std;
 
//运算符优先级比较,括号优先级最高,然后是乘除,再加减
bool priority(const char &a,const char &b){
    if(a == '(') return false;
    if(((a == '+')||(a == '-'))&&((b == '*')||(b == '/')))
        return false;
    return true;
}

//根据栈顶运算符弹出两个元素进行运算,并把结果压入数字栈顶
void compute(stack<int> &si,stack<char> &sc){
    int b = si.top();
    si.pop();
    int a = si.top();
    si.pop();
    //运算符栈顶
    char op = sc.top();
    sc.pop();
    if(op == '+') a = a + b;
    else if(op == '-') a = a - b;
    else if(op == '*') a = a * b;
    else if(op =='/') a = a / b;
    //计算结果压入数字栈顶
    si.push(a);
}
 
 int getResult(string &str){
    stack<int> si;
    stack<char> sc;
    //给整个表达式加上()
    str = "("+str+")";
    bool flag = false;
    for(int i = 0;i < str.size(); ++i){
        //遇到左括号假如到运算栈
        if(str[i]=='('){
            sc.push('(');
        }
        //遇到右括号
        else if(str[i] == ')'){
            //弹出开始计算,直到遇到左括号
            while(sc.top() != '('){
                compute(si,sc);
            }
            //弹出左括号
            sc.pop();
        }
        //运算符比较优先级
        else if (flag){
            while(priority(sc.top(),str[i])){
                compute(si,sc);
            }
            //现阶段符号入栈等待下次计算
            sc.push(str[i]);
            flag = false;
        }
        //数字
        else{
            //开始记录
            int j = i;
            //正负号
            if(str[j] == '+'||str[j] == '-') i++;
            while(isdigit(str[i])){
                i++;
            }
            //截取数字部分
            string temp = str.substr(j,i - j);
            si.push(stoi(temp));
            //注意外层i还会+1,所以这里-1
            i--;
            //数字完了肯定是符号
            flag = true;
        }
    }
    //返回栈顶元素,为最终结果。
    return si.top();
 }
int main() {
    string str;
    cin >> str;
      
    cout << getResult(str) << endl; 
}
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值