#ifndef INCLUD
#include <bits/stdc++.h>
#else
#include <iostream>
#inclucde <map>
#inclucde <string>
#inclucde <stack>
#endif
using namespace std;
//四则运算
int calulateValue(int x, int y, char ch)
{
switch(ch) {
case '+':
return x + y;
case '-':
return x -y;
case '*' :
return x * y;
case '/':
return x / y;
}
return 0;
}
void caculateCirculationValue(stack<int> &numStack, stack<char> &chStack)
{
int y = numStack.top();
numStack.pop();
int x = numStack.top();
numStack.pop();
char ch = chStack.top();
chStack.pop();
int sum = calulateValue(x, y, ch);
numStack.push(sum);
}
/*
题意:
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
思路:利用数字栈、运算栈与运算符之间的优先级实现。
实现步骤:
第一步,如果是数字,则输入数字栈;
第二步,如果是左括号,则输入运算符栈;
第三步,如果是右括号,则匹配相对应的左括号循环运算
第四步:否则根据优先级进行循环计算(优先级:+、-小于*、/)
*/
int caculateSumValue(string strIn)
{
string strNum; //数字字符串
stack<int> numStack; //存储数字栈
stack<char> chStack; //存储字符栈
map<char, int> priorityMap; //算法的优先级
priorityMap.emplace('=', 0);
priorityMap.emplace('+', 1);
priorityMap.emplace('-', 1);
priorityMap.emplace('*', 2);
priorityMap.emplace('/', 2);
strIn += '='; // 添加等号的优先级
for(int i = 0; i < strIn.length(); i++) {
if(isdigit(strIn[i])) { //数字
strNum += strIn[i];
} else {
if(strNum.size()) { //数字压入栈
int sum = 0;
for(int i = 0; i < strNum.size(); i++) {
sum = sum*10 + strNum[i] - '0'; //字符转化数字
}
numStack.push(sum);
}
strNum = ""; // 清空数字字符串
if(strIn[i] == '(' || strIn[i] == '{' || strIn[i] == '[') { //左括号,压入字符栈
chStack.push(strIn[i]);
} else if (strIn[i] == ')') { //有括号,利用左括号循环运算
while(!chStack.empty() && chStack.top() != '(') {
caculateCirculationValue(numStack, chStack);
}
chStack.pop();
} else if (strIn[i] == ']') { //有括号,利用左括号循环运算
while(!chStack.empty() && chStack.top() != '[') {
caculateCirculationValue(numStack, chStack);
}
chStack.pop();
} else if (strIn[i] == '}') { //有括号,利用左括号循环运算
while(!chStack.empty() && chStack.top() != '{') {
caculateCirculationValue(numStack, chStack);
}
chStack.pop();
} else {
//否则根据优先级进行循环计算(优先级:+、-小于*、/)
if(strIn[i] == '-' && (strIn[i-1] == '(' || strIn[i-1] == '[' || strIn[i-1] == '{')) { //如果是负数,则前面加0
numStack.push(0);
}
while(!chStack.empty() && priorityMap[strIn[i]] <= priorityMap[chStack.top()]) { //利用优先级进行循环计算
caculateCirculationValue(numStack, chStack);
}
chStack.push(strIn[i]);
}
}
}
return numStack.top();
}
int main()
{
string strIn;
while(cin>>strIn) {
cout<<caculateSumValue(strIn)<<endl;
}
}