题目描述
对于一个不存在括号的表达式进行计算(包含加减乘除四种运算符,除法为向下取整)。
输入
多组数据,每组数据占据一行。
输出
输出计算结果。
样例输入
6/2+3+34
734/2-562-7*8
样例输出
18
199
// 题目:计算表达式
// 日期:2021/7/13
// 详情:对于一个不存在括号的表达式进行计算(包含加减乘除四种运算符,除法为向下取整)。
// XWQ
#include <bits/stdc++.h>
using namespace std;
int help(int a, int b, char op){
switch (op){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
}
return 0;
}
int cal(string str){
stack<int> num;
stack<char> op;
int priority[300];
priority['+'] = priority['-'] = 0;
priority['/'] = priority['*'] = 1;
int n = str.size(),a,b,now=0;
for(int i=0; i<n; i++){
if(str[i]>='0' && str[i]<='9') // 1.数字入num栈
now = now*10 + str[i] - '0'; // 1*.转换多位数
else{ // 2.符号
num.push(now);
now = 0;
if(!op.empty()){
while(!op.empty() && priority[str[i]]<=priority[op.top()]){ // 2*.根据优先级计算
a = num.top(); num.pop();
b = num.top(); num.pop();
num.push(help(b,a,op.top()));
op.pop();
}
}
op.push(str[i]);
}
}
num.push(now);
while(!op.empty()){ // 3.计算剩余栈内的表达式
int a = num.top(); num.pop();
int b = num.top(); num.pop();
num.push(help(b,a,op.top()));
op.pop();
}
return num.top();
}
int main(){
string str;
while(cin >> str){
printf("%d\n",cal(str));
}
}