火星文计算(C++)

#include <csignal>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;

void compute(stack<int>& s1, stack<char>& s2){
    int b = s1.top();
    s1.pop();
    int a = s1.top();
    s1.pop();
    char ch = s2.top();
    s2.pop();
    int sum = 0;
    if(ch == '#'){
        sum =  4*a+3*b+2;
    }
    else{
        sum = 2*a+b+3;
    }
    s1.push(sum);
}


//比较优先级,低于栈顶优先级,则计算,高于则压栈
bool pority(char a, char b){
    if(a == '('){
        return false;
    }
    else if(a == '$'&&b == '#'){
        return false;//高于,则压栈
    }
    else{
        return true;//低于,计算
    }
}
int main() {
    string s;
    getline(cin, s);
    s += ')';//添加一个右括号,方便计算
    stack<int> num;//数字
    stack<char> symbol;//符号
    symbol.push('(');//先压入一个左括号,方便计算
    string temp = "";//存储数字
    for(int i = 0; i < s.size();i++){
        if(s[i]>='0'&&s[i]<='9'){
            temp += s[i];
        }
        else if(s[i] == ')'){//是括号
            //先将数字插入栈中
            num.push(stoi(temp));
            temp = "";
            while(symbol.top()!= '('){
                compute(num, symbol);
            }
            symbol.pop();//弹出左括号
        }
        else{//是符号
            //先将数字插入栈中
            num.push(stoi(temp));
            temp = "";
            //与栈顶元素比较优先级
            while(pority(symbol.top(), s[i])){
                compute(num,symbol);
            }
            symbol.push(s[i]);//高于则压栈
        }
    }
    cout << num.top() << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值