Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
3 + 2 * 4 - 5 - 6 / 3
拆分为
3
2 * 4
-5
-6 / 3
最后求和即可
class Solution {
public:
int calculate(string s) {
stack<int> data;
string operand{"+"}; // 操作数带正负号,最后对所有数做加法即可
char op = '+'; // 保存上一个操作符,默认为加号
s += '$'; // 加一个结束符,否则最后一个数没有后续符号,不会被操作
for (auto& x : s) {
if (x == ' ') {
continue;
}
if (isdigit(x)) { // 如果是数字,则添加到操作数后
operand += x;
} else { // 如果是加减号则先把数入栈,乘除号则直接计算
if (op == '*') {
data.top() *= stoi(operand);
} else if (op == '/') {
data.top() /= stoi(operand);
} else {
data.emplace(stoi(operand));
}
operand = x == '-' ? "-" : "+";
op = x;
}
}
int res = 0;
while (!empty(data)) {
res += data.top();
data.pop();
}
return res;
}
};