#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;
}
火星文计算(C++)
最新推荐文章于 2024-06-19 12:59:51 发布