You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.1 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
// 2013NOIP普级组第二题表达式的值参考洛谷题解
// https://blog.csdn.net/u014542643/article/details/78435113
/*
stack
(1) +*
(2)
*/
/**
*
* @param str
* @return
*/
int StrToInt(string str) {
istringstream stream1;
stream1.str(str);
int i;
stream1 >> i;
return i;
}
int main() {
string x;
getline(cin, x);
//字符串的长度
int len = x.length();
//数字栈
stack<int> numStack;
//操作符栈
stack<char> opStack;
//遍历每一个字符
for (int i = 0; i < len;) {
string s = "";
while (x[i] >= '0' && x[i] <= '9') {
s += x[i];
i++;
}
//数字入栈
if (s != "") {
numStack.push(StrToInt(s));
if (!opStack.empty() && opStack.top() == '*') {
//如果发现在运算符栈中栈顶是*,那么需要把数字栈中两个数字拿出来,然后相乘再放回去
int a = numStack.top();
numStack.pop();
int b = numStack.top();
numStack.pop();
numStack.push(a * b);
//乘号出栈
opStack.pop();
}
}
//操作符,这里只处理*即可。
if (x[i] == '*') {
opStack.push(x[i]);
}
//如果是+号,就不需要处理了,但不管是数字还是符号,都需要向后再走一个,好读取下一个。
i++;
}
// 将结果加在一起
int sum = 0;
while (!numStack.empty()) {
int a = numStack.top();
numStack.pop();
sum += a;
}
cout << sum << endl;
return 0;
}