class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
long long legalExp(string str) {
stack<long long> nums;
int n = str.size();
for (int i = 0; i < n; ++i) {
char c = str[i];
if (isdigit(c)) {
long long num = 0;
while (i < n && isdigit(str[i])) {
num = num * 10 + (str[i] - '0');
++i;
}
nums.push(num);
} else if (c == '+' || c == '-' || c == '*') {
long long b = nums.top();
nums.pop();
long long a = nums.top();
nums.pop();
if (c == '+') {
nums.push(a + b);
} else if (c == '-') {
nums.push(a - b);
} else if (c == '*') {
nums.push(a * b);
}
}
}
return nums.top();
}
};